Java Exception Handling

Source: Internet
Author: User
Tags exit in

Java Error handling with Exceptions

The basic philosophy of Java is that "badly formed code would not be run."

The ideal time to catch a error is at compile time, before you even try-to-run the program. However, not all errors can is detected at compile time. The rest of the problems must is handled at run time through some formality that allows the originator of the error to PAS s appropriate information to a recipient who'll know how to handle the difficulty properly.

     the word "exception" is meant in the sense of ' I take exception to that. ' At the point where the problem occurs, you might isn't know what does with it, but you do know that's you can ' t just continue on merrily; You must stop, and somebody, somewhere, must figure out what to do. But you don ' t has enough information in the current context to fix the problem. So you hand the problem off to a higher context where someone are qualified to make the proper decision (much like a chain of command).

The other rather significant benefit of exceptions are that they clean up error handling code. Instead of checking for a particular the error and dealing with it at multiple places in your program, you no longer need to C Heck at the point of the method call (since the exception would guarantee that someone catches it). And, you need to handle the problem in only one place, the so-called exception handler. This saves your code, and it separates the code that describes "what" want to does from the code that's executed when thin GS go awry. In general, reading, writing, and debugging code becomes much clearer with exceptions than when using the Handling.

Because exception Handling is the only official to that Java reports errors, and it's enforced by the Java compiler, the Re is only so many examples the can is written in this book without learning about exception handling.

1. Basic Exceptions

An exceptional condition was a problem that prevents the continuation of the the method or scope that you ' re in. It ' s important to distinguish an exceptional condition from a normal problem, in which you have enough information in the Current context to somehow cope with the difficulty. With a exceptional condition, you cannot continue processing because you don't have the information necessary to deal wit h the problem in the current context. All your can do are jump out of the current context and relegate this problem to a higher context. This is a happens when you throw a exception.

     division is a simple example. If you ' re about to divide by zero, it's worth checking for that condition. But what does it mean that the denominator is zero? Maybe you know, in the context of the problem you ' re trying to solve in that particular method, what to deal with a zero de Nominator. But if it's an unexpected value, you can ' t deal with it and so must a exception rather than continuing along that E Xecution path.

     when you to throw an exception, several things happen. First, the exception object is a created in the same, and the any Java object was created:on the heap, with new. Then the current path of execution (the one couldn ' t continue) was stopped and the reference for the exception object I s ejected from the current context. At this point the exception handling mechanism takes-over and begins-look for a appropriate place to continue Executin G The program. This appropriate place is the exception handler, whose job was to recover from the problem so the program can either try an Other tack or just continue.

As a simple example of throwing an exception, consider an object reference called T. It's possible that's might be passed a reference the hasn ' t been initialized, so you might want to check before trying To call a method using the that object reference. You can send information about the error to a larger context by creating an object representing your information and "th Rowing "It out of your current context. This was called throwing an exception. Here's what it looks like:

if (t = = null)

throw new NullPointerException ();

This throws the exception, which allows you-in the current context-to abdicate responsibility for thinking about the issue further. It ' s just magically handled somewhere else.

2. catching an exception

If a method throws an exception, it must assume that exception would be is "caught" and dealt with. One of the advantages of exception handling is so it allows you and concentrate on the problem your ' re trying to solve in One place, and then deal with the errors from that code in another place.

To see what's exception is caught, you must first understand the concept of a guarded region. This was a section of code, might produce exceptions and is followed by the code to handle those exceptions.

(1) The TRY Block

If you ' re inside a method and you throw an exception (or another method to call within this method throws an exception), That method would exit in the process of throwing. If you don't want a throw to exit the method, you can set up a special block within, the exception. This was called the try block because you "try" your various method calls there. The try block is a ordinary scope preceded by the keyword try:

try {

Code that might generate exceptions

}

If you were checking for errors carefully in a programming language the didn ' t support exception handling, you ' d has to Surround every method call with Setup and error testing code, even if your call the same method several times. With exception handling, you put everything in a try block and capture all of the exceptions in one place. This means your code was much easier to write and read because the goal of the code are not confused with the error checking .

(2) Exception handlers

Of course, the thrown exception must end up someplace. This "place" is the exception handler, and there's one for every exception type you want to catch. Exception handlers immediately follow the try block and is denoted by the keyword catch:

try {

Code that might generate exceptions

} catch (Type1 id1) {

Handle Exceptions of Type1

} catch (Type2 Id2) {

Handle Exceptions of Type2

} catch (Type3 id3) {

Handle Exceptions of Type3

}

Each catch clause (exception handler) is a little method, a takes one and only one argument of type. The identifier (ID1, Id2, and so on) can is used inside the handler, just like a method argument. Sometimes never use the identifier because the type of the exception gives you enough information to deal with the exc Eption, but the identifier must still is there.

Each catch clause (exception handler) is a little method, a takes one and only one argument of type. The identifier (ID1, Id2, and so on) can is used inside the handler, just like a method argument. Sometimes never use the identifier because the type of the exception gives you enough information to deal with the exc Eption, but the identifier must still is there.

The handlers must appear directly after the try block. If an exception are thrown, the exception handling mechanism goes hunting for the first handler with a argument that match Es the type of the exception. Then it enters this catch clause, and the exception is considered handled. The search for handlers stops once, the catch clause is finished. Only the matching catch clause executes; It's not a-like a-switch statement in which you need a broke after each case to prevent the remaining ones from executing.

Note that within the try block, a number of different method calls might generate the same exception E handler.

3. termination vs. Resumption

There is both basic models in exception handling theory. In termination (which are what Java and C + + support), you assume that the error was so critical that there's No to get B Ack to where the exception occurred. Whoever threw the exception decided that there is no-to-salvage the situation, and they don ' t want to come back.

     the alternative is called resumption. It means that the exception handler are expected to does something to rectify the situation, and then the faulting method is Retried, presuming success the second time. If you want resumption, it means you still hope to continue execution after the exception are handled. In the this case, your exception are more like a method Call-which are how do you should set up situations in Java in which you wan T resumption-like behavior. (That's, don ' t throw a exception; Call a method that fixes the problem.) Alternatively, place your try block inside a while loop this keeps reentering the try block until the result is Satisfacto Ry.

Historically, programmers using operating systems, supported Resumptive exception handling eventually ended up using T Ermination-like code and skipping resumption. So although resumption sounds attractive at first, it isn ' t quite so useful in practice. The dominant reason is probably, the coupling that results; Your handler must often be aware of where the exception are thrown, and contain nongeneric code specific to the throwing Lo cation. This makes the code difficult to write and maintain, especially for large systems where the exception can be generated fro M many points.

4. The exception specification

      in Java, you ' re encouraged to inform the client programmer, who calls your method, Of the exceptions that might is thrown from your method. This was civilized, because the caller can know exactly what code to write to catch all potential exceptions. Of course, if source code is available, the client programmer could hunt through and look for throw statements, but often A library doesn ' t come with sources. To prevent the from being a problem, Java provides syntax (and forces-you-use-syntax) to-allow-you-to-politely te ll the client programmer what exceptions this method throws and so the client programmer can handle them. This is the exception specification and it's part of the method declaration, appearing after the argument list.

The exception specification uses an additional keyword, throws, followed by a list of all the potential exception types. So your method definition might look like this:

void F () throws Toobig, Toosmall, Divzero {//...

If you say

void F () {//...

It means that no exceptions is thrown from the method.

5. performing cleanup with finally

There ' s often some piece of code that you want to execute whether or isn't an exception is thrown within a try block. This usually pertains to some operation other than memory recovery (since that's taken care of by the garbage collector). To achieve this effect, you use a finally clause at the end of the the exception handlers. The full picture of a exception handling section is thus:

try {

The guarded region:dangerous activities

That might throw A, B, or C

} catch (A A1) {

Handler for Situation A

} catch (B B1) {

Handler for Situation B

} catch (C C1) {

Handler for Situation C

} finally {

Activities that happen every time

}

From the output, you can see that whether or not a exception is thrown, the finally clause are always executed.

6. Summary

Improved error recovery is one of the most powerful ways so you can increase the robustness of your code. Error recovery is a fundamental concern for every program "you write" but it's especially important in Java, where one of T He primary goals is-to-create program, for others to use. To create a robust system, each component must is robust. By providing a consistent error-reporting model with exceptions, Java allows components to reliably communicate problems t O Client code.

The goals for exception handling in Java is to simplify the creation of large, reliable programs using less code than cur Rently possible, and to does so with more confidence that your application doesn ' t has an unhandled error. Exceptions is one of those features that provide immediate and significant benefits to your project.

Java Exception Handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.