Catching Exceptions

     

In the preceding examples, all of the methods throw an exception up to the caller. But you catch exceptions to handle them in your code.

You can declare one or more catch blocks for each try block. There can be no code between the end of the try block and the beginning of the catch block.

Inside a try block, if your code generates an exception, processing stops immediately, and the runtime checks each subsequent catch block to match the exception type declared with the exception type thrown. Upon finding a match, it enters the catch block and executes whatever handling code is in there. Like this:

 

 void someMethod() {    throw new UnknownHostException();    System.out.println("Uh-oh!");    //this line will never be printed. } catch (UnknownHostException uhe) {      System.out.println("I will be printed"); //ok } 

Code inside a catch block may throw exceptions. Like this:

 

 void someMethod(){ try {     //connect to a database here     //a SQLException happens. Oh no.     throw new SQLException("Things are not               what they seem"); } catch (SQLException sqle) {     //code here to tell the user about the problem     //with their query     //Since there was a problem with the database,     //let's shut down the connection to it.     //But guess whatclosing the connection throws a     //SQLException too!     //so we have to do it again...     try {         connection.close();     } catch (SQLException se) {         //handle the potential         //connection.close() exception     } // end inner catch } // end outer catch } // end method 

Code inside a catch block can be well-employed to clean up any resources such as database connections or file streams that should be closed if an exception is thrown. Consequently, catch blocks can also contain try/catch blocks.

If you define a try/catch block, and none of the code in the try block generates an exception, the code inside all catch blocks is completely ignored.

You can rethrow an exception after you catch it. The following is okay:

 

 try {     throw new KittyException(); } catch (KittyException ke) {     throw new DogException("My dog message. " + ke.getMessage()); } 



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

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