Catching Multiple Exceptions


It is possible for a single line of code to generate more than one exception. Each exception can be of a different exception type. A method that throws more than one exception can list each exception type individually:

 public void send() throws ObjectStreamException, UnknownHostException 

If both exceptions derive from the same class, you can instead declare that the method throws an exception of the common supertype:

 public void send() throws Exception 

The try-catch block can have multiple catch clauses, each representing an exception that might be thrown.

 try {    new Student("a b c d"); } catch (StudentNameFormatException e) {    ... } catch (NoSuchElementException e) {    ... } 

If code within the TRy block throws an exception, the Java VM transfers control to the first catch block. If the type of the exception thrown matches the type declared in the catch clause, the VM executes code within that catch block. Otherwise, the VM transfers control to the next catch block, and so on. Once code in a catch block is executed, the VM ignores all other catch blocks.

In the following code, the second catch block catches any exception that is of type Exception. Since all (normal) exceptions extend from Exception, this "catch-all" block will trap any application exception other than StudentNameFormatException, which you already trapped with the first catch block.

 try {    new Student("a b c d"); } catch (StudentNameFormatException e) {    ... } catch (Exception e) {    ... } 

A catch-all is useful for trapping any unexpected exceptions. You should usually include a catch-all only in your top-level class, the one closest to the user interface layer. About the only thing you will be able to do in the catch-all is to log the error and possibly show something to the end user. What you gain is the ability to keep the application from crashing or visibly failing.

Use extreme discretion when introducing a catch-all. If you introduce new code in the try block or in the code it calls, this code can generate a new exception. The problem is that you might be unaware of the new exception, even if it is a checked exception. Hiding errors is bad.



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net