13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

3.2 Fundamental Language Elements77Example 3.20 Catching different kinds of excepti<strong>on</strong>stry {for (i = 0; i < max; i++) {someobj.methodB(param1, i);} // next i} catch (SpecialExcepti<strong>on</strong> sp) {System.out.println(sp.whatWentWr<strong>on</strong>g());} catch (AlternateExcepti<strong>on</strong> alt) {alt.attemptRepair(param1);} catch (Excepti<strong>on</strong> e) {// do the error handling here:System.out.println(e.toString());e.printStackTrace();}// c<strong>on</strong>tinues executi<strong>on</strong> here after any catchExample 3.21 Output from printStackTrace()java.lang.Excepti<strong>on</strong>: Error in the fraberstam.at InnerMost.doOtherStuff(InnerMost.java:6)at MidModule.doStuff(MidModule.java:7)at AnotherClass.doSomething(AnotherClass.java:11)at ExceptExample.main(ExceptExample.java:14)AnotherClass, which itself had been called from line 14 in theExceptExample class’ main() method.We want to menti<strong>on</strong> <strong>on</strong>e more piece of syntax for the try/catch block.Since executi<strong>on</strong> may never get to all of the statements in a try block (the excepti<strong>on</strong>may make it jump out to a catch block), there is a need, sometimes,for some statements to be executed regardless of whether all the try codecompleted successfully. (One example might be the need to close an I/O c<strong>on</strong>necti<strong>on</strong>.)For this we can add a finally clause after the last catch block. Thecode in the finally block will be executed (<strong>on</strong>ly <strong>on</strong>ce) after the try or afterthe catch—even if the path of executi<strong>on</strong> is about to leave because of throwingan excepti<strong>on</strong> (Example 3.22).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!