Using Finally

     

The finally keyword is used after a try/catch block to indicate that the code inside the finally block should be executed whether the code inside the try block generates an exception or not. No matter what happens (unless someone pulls the plug on your box or externally kills your JVM process), the code in your finally block will run.

Do it like this:

 

 try { ... } catch (SomeEx se) {  ... } finally {  //put the code you want to run to matter what here. } 

Note that although the preceding code is how you will see it used 99% of the time, you can use the finally block without a catch block.

The finally statement is very useful, especially for doing complex operations involving files, a database, or a network connection, because there can be a lot to clean up if anything goes wrong (or even if it goes right!).

However, be careful of one subtle use with the use of finally . If your code throws an exception other than the one you are catching, and enters a finally block, that original exception will be totally lost if you throw a new, different exception inside your finally block. That is a mouthful. Or a mindful. Or whatever. Look at this:

 

 InputStream in; try {    //do something with in } catch (IOException ioe) {    JOptionPane.showMessageDialog(null, "Error! " + ioe.getMessage()); } finally {      try {          in.close(); //could throw      }catch (IOException ioe) {          // this hides the original exception          } } 

Note that the finally clause will not execute if the catch block calls System.exit(); .

So a finally clause is a good thing, and can help keep you from duplicating code.



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