error handling with exceptions 2015-5-41. concepts c and other earlier languages often had multiple...

33
Error Handling with Exceptions 22/6/27 1

Upload: brennan-shoe

Post on 16-Dec-2015

217 views

Category:

Documents


1 download

TRANSCRIPT

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

Error Handling with Exceptions

23/4/18 1

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

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."

23/4/18 2

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

• 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

23/4/18 3

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

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.

23/4/18 4

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

• 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.

23/4/18 5

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

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

23/4/18 6

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

• 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

23/4/18 7

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

Catching an exception

• The concept of a guarded region. • The try block • Exception handlers

23/4/18 8

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

Guarded region

• The guarded region is a section of code that might produce exceptions and is followed by the code to handle those exceptions.

23/4/18 9

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

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

23/4/18 10

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

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.

23/4/18 11

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

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.

23/4/18 12

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

Exception handlers: Syntax

23/4/18 13

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

• 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.

23/4/18 14

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

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.

23/4/18 15

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

• 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.

23/4/18 16

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

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.

23/4/18 17

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

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.

23/4/18 18

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

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.

23/4/18 19

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

• 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:

23/4/18 20

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

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)

23/4/18 21

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

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.

23/4/18 22

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

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

23/4/18 23

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

• 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.

23/4/18 24

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

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.

23/4/18 25

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

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.

23/4/18 26

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

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.

23/4/18 27

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

Syntax

23/4/18 28

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

What’s finally for?

• The finally clause is necessary when you need to set something other than memory back to its original state.

23/4/18 29

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

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.

23/4/18 30

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

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.

23/4/18 31

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

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.

23/4/18 32

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

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.

23/4/18 33