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
try throws no exception y - y y
try throws a handled exception y y y y
try throws an unhandled exception y - y -

Here, "bottom" refers simply to any code which follows the finally block, as shown here :

final class Bottom {

  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
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -