|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
You associate exception handlers with atryblock by providing one or more catch blocks directly after the try. No code can be between the end of thetryand the beginning of the firstcatchstatement:Eachtry { ... } catch (ExceptionType name) { ... } catch (ExceptionType name) { ... } ...catchblock is an exception handler and handles the type of exception indicated by its argument. The argument type,ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from theThrowableclass. The handler can refer to the exception withname.The
catchblock contains a series of statements. These statements are executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whoseExceptionTypematches the type of the exception thrown. The system considers it a match if the thrown object can legally be assigned to the exception handler’s argument.Here are two exception handlers for writeList method--one for two types of checked exceptions that can be thrown within the try block:
The first handler shown prints an error message and throws a runtime exception that halts the program. Thowing exceptions is covered in detail in the section How to Throw Exceptionstry { ... } catch (FileNotFoundException e) { System.err.println("FileNotFoundException: " + e.getMessage()); throw new RuntimeException(e); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); }. Although somewhat contrived, this might be the behavior you want. Suppose this code is a file-based implementation of the data access layer in a larger system—you don’t want to pass implementation specific exceptions up to the higher-level business-object layer. Therefore, the
FileNotFoundExceptionhere should halt the program. In the second handler, the exception gets caught and the program continues to execute. However, exception handlers can do more. They can do error recovery, prompt the user to make a decision, or propogate the error up to a higher-level handler using chained exceptions, as described in the next section.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.