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 Elements75Java provides the try/catch/throw mechanism for more sophisticatederror handling. It avoids a lot of unnecessary checking and passing <strong>on</strong> of errors.The <strong>on</strong>ly parts of a Java program that need to deal with an error are those thatknow what to do with it.The throw in Java is really just a n<strong>on</strong>local “goto”—it will branch the executi<strong>on</strong>of your program to a locati<strong>on</strong> which can be quite far away from themethod where the excepti<strong>on</strong> was thrown. But it does so in a very structuredand well-defined manner.In our simple example of A calling B calling C calling D, D implementedas a Java method can throw an excepti<strong>on</strong> when it runs into an error. C<strong>on</strong>trolwill pass to the first enclosing block of code <strong>on</strong> the call stack that c<strong>on</strong>tains acatch for that kind of excepti<strong>on</strong>. So A can have code that will catch an excepti<strong>on</strong>,and B and C need not have any error handling code at all. Example 3.17dem<strong>on</strong>strates the syntax.Example 3.17 A simple try/catch blocktry {for (i = 0; i < max; i++) {someobj.methodB(param1, i);}} catch (Excepti<strong>on</strong> e) {// do the error handling here:System.out.println("Error encountered. Try again.");}// c<strong>on</strong>tinues executi<strong>on</strong> here after successful completi<strong>on</strong>// but also after the catch if an error occursIn the example, if any of the calls to methodB() in the for loop goawry—that is, anywhere inside methodB() or whatever methods it may call anexcepti<strong>on</strong> is thrown (and assuming those called methods d<strong>on</strong>’t have their owntry/catch blocks), then c<strong>on</strong>trol is passed up to the catch clause in our example.The for loop is exited unfinished, and executi<strong>on</strong> c<strong>on</strong>tinues first with thecatch clause and then with the statements after the catch.How does an error get thrown in the first place? One simply creates anExcepti<strong>on</strong> object and then throws the excepti<strong>on</strong> (Example 3.18).

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

Saved successfully!

Ooh no, something went wrong!