Presentation is loading. Please wait.

Presentation is loading. Please wait.

Error Handling with Exceptions 2015-5-41. Concepts C and other earlier languages often had multiple error-handling schemes, and these were generally established.

Similar presentations

Presentation on theme: "Error Handling with Exceptions 2015-5-41. Concepts C and other earlier languages often had multiple error-handling schemes, and these were generally established."— Presentation transcript:

1 Error Handling with Exceptions 2015-5-41

2 Concepts C and other earlier languages often had multiple error-handling schemes, and these were generally established by convention and not as part of the programming language. Typically, you returned a special value or set a flag, and the recipient was supposed to look at the value or the flag and determine that something was amiss. However, as the years passed, it was discovered that programmers who use a library tend to think of themselves as invincible—as in "Yes, errors might happen to others, but not in my code." 2015-5-42

3 The solution is to take the casual nature out of error handling and to enforce formality. The word "exception" is meant in the sense of "I take exception to that." The other rather significant benefit of exceptions is that they tend to reduce the complexity of error-handling code 2015-5-43

4 Basic exceptions An exceptional condition is a problem that prevents the continuation of the current method or scope. 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. 2015-5-44

5 When you throw an exception, several things happen. First, the exception object is created in the same way that any Java object is created: on the heap, with new. Then the current path of execution (the one you couldn’t continue) is stopped and the reference for the exception object is ejected from the current context. At this point the exception-handling mechanism takes over and begins to look for an appropriate place to continue executing the program. This appropriate place is the exception handler, whose job is to recover from the problem so the program can either try another tack or just continue. 2015-5-45

6 Exception arguments As with any object in Java, you always create exceptions on the heap using new, which allocates storage and calls a constructor. There are two constructors in all standard exceptions: The first is the default constructor, and the second takes a string argument so that you can place pertinent information in the exception 2015-5-46

7 The keyword throw produces a number of interesting results. After creating an exception object with new, you give the resulting reference to throw. You can throw any type of Throwable, which is the exception root class 2015-5-47

8 Catching an exception The concept of a guarded region. The try block Exception handlers 2015-5-48

9 Guarded region The guarded region is a section of code that might produce exceptions and is followed by the code to handle those exceptions. 2015-5-49

10 The try block If you’re inside a method and you throw an exception (or another method that you call within this method throws an exception), that method will 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 that method to capture the exception. This is called the try block because you "try" your various method calls there. The try block is an ordinary scope preceded by the keyword try 2015-5-410

11 try block - Syntax With exception handling, you put everything in a try block and capture all the exceptions in one place. This means your code is much easier to write and read because the goal of the code is not confused with the error checking. 2015-5-411

12 Exception handlers 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 are denoted by the keyword catch. 2015-5-412

13 Exception handlers: Syntax 2015-5-413

14 Each catch clause (exception handler) is like a little method that takes one and only one argument of a particular type. The identifier (id1, id2, and so on) can be used inside the handler, just like a method argument. Sometimes you never use the identifier because the type of the exception gives you enough information to deal with the exception, but the identifier must still be there. The handlers must appear directly after the try block. 2015-5-414

15 Termination vs. resumption There are two basic models in exception-handling theory. Java supports termination, in which you assume that the error is so critical that there’s no way to get back to where the exception occurred. Whoever threw the exception decided that there was no way to salvage the situation, and they don’t want to come back. 2015-5-415

16 The alternative is called resumption. It means that the exception handler is expected to do 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 is handled. 2015-5-416

17 Creating your own exceptions You’re not stuck using the existing Java exceptions. The Java exception hierarchy can’t foresee all the errors you might want to report, so you can create your own to denote a special problem that your library might encounter. 2015-5-417

18 Exceptions and logging You may also want to log the output using the java.util.logging facility. The static Logger.getLogger( ) method creates a Logger object associated with the String argument (usually the name of the package and class that the errors are about) which sends its output to System.err. The easiest way to write to a Logger is just to call the method associated with the level of logging message. 2015-5-418

19 The exception specification In Java, you’re encouraged to inform the client programmer, who calls your method, of the exceptions that might be thrown from your method. This is civilized, because the caller can then know exactly what code to write to catch all potential exceptions. 2015-5-419

20 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: 2015-5-420

21 Catching any exception It is possible to create a handler that catches any type of exception. You do this by catching the base-class exception type Exception (there are other types of base exceptions, but Exception is the base that’s pertinent to virtually all programming activities) 2015-5-421

22 The stack trace The information provided by printStackTrace( ) can also be accessed directly using getStackTrace( ). This method returns an array of stack trace elements, each representing one stack frame. Element zero is the top of the stack, and is the last method invocation in the sequence (the point this Throwable was created and thrown). The last element of the array and the bottom of the stack is the first method invocation in the sequence. 2015-5-422

23 Rethrowing an exception Sometimes you’ll want to rethrow the exception that you just caught, particularly when you use Exception to catch any exception. Since you already have the reference to the current exception, you can simply rethrow that reference 2015-5-423

24 Rethrowing an exception causes it to go to the exception handlers in the nexthigher context. Any further catch clauses for the same try block are still ignored. In addition, everything about the exception object is preserved, so the handler at the higher context that catches the specific exception type can extract all the information from that object. 2015-5-424

25 Exception chaining Often you want to catch one exception and throw another, but still keep the information about the originating exception—this is called exception chaining. Prior to JDK 1.4, programmers had to write their own code to preserve the original exception information, but now all Throwable subclasses have the option to take a cause object in their constructor. 2015-5-425

26 Standard Java exceptions The Java class Throwable describes anything that can be thrown as an exception. There are two general types of Throwable objects ("types of = "inherited from"). Error represents compile-time and system errors that you don’t worry about catching (except in very special cases). Exception is the basic type that can be thrown from any of the standard Java library class methods and from your methods and runtime accidents. So the Java programmer’s base type of interest is usually Exception. 2015-5-426

27 Performing cleanup with finally There’s often some piece of code that you want to execute whether or not 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 clause4 at the end of all the exception handlers. 2015-5-427

28 Syntax 2015-5-428

29 What’s finally for? The finally clause is necessary when you need to set something other than memory back to its original state. 2015-5-429

30 Using finally during return Because a finally clause is always executed, it’s possible to return from multiple points within a method and still guarantee that important cleanup will be performed. 2015-5-430

31 Exception restrictions When you override a method, you can throw only the exceptions that have been specified in the base-class version of the method. 2015-5-431

32 Exception matching When an exception is thrown, the exception-handling system looks through the "nearest“ handlers in the order they are written. When it finds a match, the exception is considered handled, and no further searching occurs. Matching an exception doesn’t require a perfect match between the exception and its handler. A derived-class object will match a handler for the base class. 2015-5-432

33 Summary Exceptions are integral to programming with Java; you can accomplish only so much without knowing how to work with them. For that reason, exceptions are introduced at this point in the book— there are many libraries (like I/O, mentioned earlier) that you can’t use without handling exceptions. 2015-5-433

Download ppt "Error Handling with Exceptions 2015-5-41. Concepts C and other earlier languages often had multiple error-handling schemes, and these were generally established."

Similar presentations

Ads by Google