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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

76Chapter 3An Experienced Programmer’s Introducti<strong>on</strong> to JavaExample 3.18 Throwing an Excepti<strong>on</strong>, step by stepExcepti<strong>on</strong> ex = new Excepti<strong>on</strong>("Bad News");throw ex;Since there is little point in keeping the reference to the object for the localmethod—executi<strong>on</strong> is about to leave the local method—there is no need todeclare a local variable to hold the excepti<strong>on</strong>. Instead, we can create the excepti<strong>on</strong>and throw it all in <strong>on</strong>e step (Example 3.19).Example 3.19 Throwing an Excepti<strong>on</strong>, <strong>on</strong>e stepthrow new Excepti<strong>on</strong>("Bad News");Excepti<strong>on</strong> is an object, and as such it can be extended. So we can createour own unique kinds of excepti<strong>on</strong>s to differentiate all sorts of error c<strong>on</strong>diti<strong>on</strong>s.Moreover, as objects, excepti<strong>on</strong>s can c<strong>on</strong>tain any data that we might want topass back to the calling methods to provide better diagnosis and recovery.The try/catch block can catch different kinds of excepti<strong>on</strong>s muchlike cases in a switch/case statement, though with different syntax(Example 3.20).Notice that each catch has to declare the type of each excepti<strong>on</strong> andprovide a local variable to hold a reference to that excepti<strong>on</strong>. Then method callscan be made <strong>on</strong> that excepti<strong>on</strong> or references to any of its publicly available datacan be made.Remember how we created an excepti<strong>on</strong> (new Excepti<strong>on</strong>("message"))?That message can be retrieved from the excepti<strong>on</strong> with the toString()method, as shown in that example. The method printStackTrace() is alsoavailable to print out the sequence of method calls that led up to the creati<strong>on</strong>of the excepti<strong>on</strong> (Example 3.21).The excepti<strong>on</strong>’s stack trace is read top to bottom showing the mostrecently called module first. Our example shows that the excepti<strong>on</strong> occurred(i.e., was c<strong>on</strong>structed) <strong>on</strong> line 6 of the class named InnerMost, inside a methodnamed doOtherStuff(). The doOtherStuff() method was called frominside the class MidModule—<strong>on</strong> line 7—in a method named doStuff().In turn, doStuff() had been called by doSomething(), at line 11 inside

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

Saved successfully!

Ooh no, something went wrong!