Wednesday 16 March 2016

The Java Language: Bubbling Up

What if we hadn’t caught the exception? Where would it have gone? Well, if there is no enclosing try/catch statement, the exception pops up from the method in which it originated and is thrown from that method up to its caller. If that point in the calling method is within a try clause, control passes to the corresponding catch clause. Otherwise, the exception continues propagating up the call stack, from one method to its caller. In this way, the exception bubbles up until it’s caught, or until it pops out of the top of the program, terminating it with a runtime error message. There’s a bit more to it than that because in this case, the compiler might have forced us to deal with it along the way, but we’ll get back to that in a moment. Let’s look at another example. In the next figure, the method getContent() invokes the method openConnection() from within a try/catch statement. In turn, openConnec tion() invokes the method sendRequest(), which calls the method write() to send some data.

In this figure, the second call to write() throws an IOException. Since sendRe quest() doesn’t contain a try/catch statement to handle the exception, it’s thrown again from the point where it was called in the method openConnection(). Since open Connection() doesn’t catch the exception either, it’s thrown once more. Finally, it’s caught by the try statement in getContent() and handled by its catch clause. Notice that each throwing method must declare with a “throws” clause that it can throw the particular type of exception. We’ll discuss this shortly.

0 comments:

Post a Comment