Wednesday, February 16, 2011

Exceptions and control flow

When an exception occurs within a method, the control flow defined by Java can take several forms.
If an exception occurs outside a try..catch block, the exception simply propagates "up" to the caller.
If an exception occurs inside a try..catch block, then the control flow can take different forms. Here are the cases, along with indicators for which code blocks are included in the control flow :
 


Case try  catch  finally bottom return
try throws no exception y - y y y
try throws a handled exception y y y y y
try throws an unhandled exception y - y - y
Here, "bottom" refers simply to any code which follows the finally block, as shown here :
void doStuff() {
try {
//..
}catch( Exception ex ) {
//..
}finally {
//..
}/
//any code appearing here, after the finally
//block, is "bottom" code
}
There is a misconception - especially common among C programmers migrating to Java - that exceptions can be used to define ordinary control flow. This is a misuse of the idea of exceptions, which are meant only for defects or for items outside the direct control of the program.

See Also :
Checked versus unchecked exceptions
Avoid basic style errors

No comments:

Post a Comment

Chitika