|
|
|
|
The try BlockIn order to catch exceptions thrown by a set of Java statements, you must first enclose the statements within a try block:
The catch Block(s)Following the try block, you may specify a number of catch blocks:
Each catch block is an exception handler which handles the
type of exception indicated. The Java runtime system invokes the appropriate exception handler when it is the first handler in the call stack whose ExceptionType matches the type of the exception being thrown. The system considers it to be a match if the thrown exception can legally be assigned to the handler's ExceptionType. Using a Single Handler to Catch Multiple Exception TypesAt times, it might seem necessary to have many exception handlers, each handling a specific exception that your code throws. This can get pretty unwieldy -- especially if you have more catch blocks than can fit on a page or screen. To overcome this problem, try to use the exception hierarchy to reduce the number of catch blocks you have to specify. For example, if you're trying to catch all exceptions that are subclasses of IOException, all you have to do is:
If you want to catch a FileNotFoundException (a subclass of IOException) specifically, as well as catching all other IOExceptions, then you can do:
However, when you do such things, it introduces a catch-block ordering problem. For example, the following will not work:
Why not? The technique of using class inheritance to define "families" of related exceptions is very useful:
A "catch-all" BlockUnlike C++, which has a try/catch block of the form:
Java has no special syntax for a catch block for catching all exceptions. However, you can do the same thing by specifying Exception (or Throwable) as the ExceptionType in the catch block:
The following is not equivalent to the above.
The finally BlockOptionally, you may specify a finally block:
or:
The statements in the finally block are executed when the try/catch block exits, whether normally or as a result of an exception being thrown. This is very useful -- indeed, in some cases indispensable. Here's an example: Resource res = new Resource(); res.open(); // Do work with res ... res.close(); This code looks fine, but doesn't work properly when an exception gets thrown during our work with res. The close() is never executed, which leaves our resource taking up resources that should have been cleaned up. Perhaps this will result in a failure later on during the program's execution. As one solution to this problem, one could do something like:
but this results in duplicated code, especially when you're dealing with multiple exceptions. The finally block solution is much cleaner:
|
| The page was last updated February 19, 2008 |