Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between finally and write after catch

What is the difference between "finally" and write after "catch"?

For example:

public boolean example() {
    try {
        // Code
    } catch (RuntimeException e) {
        // Code
    } finally {
        return true;
    }
}

public boolean example() {
    try {
        // Code
    } catch (RuntimeException e) {
        // Code
    } 
    return true;
}
like image 288
Milton90 Avatar asked Jun 23 '13 14:06

Milton90


1 Answers

First of all, the only idiom that can even be considered a candidate is this:

try {
    // stuff
} catch (Throwable t) { 
    // handle
}
// finally stuff

Note the caught type. Only if you catch any possible exception, including such dark monsters as ThreadDeath and VirtualMachineError can you hope to unconditionally reach the code below the try-catch.

But, that's only where it begins. What if the handling code itself throws an exception? So you need at least

try { 
    // main stuff
} catch (Throwable t) {
    try { 
        // handle 
    } catch (Throwable t) { 
        // no code allowed here! Otherwise we descend into
        // infinite recursion
    }
}
// finally stuff

Now you may be beginning to realize the benefits of finally, but that's not all. Consider a quite typical scenario:

try { 
  // main stuff, may throw an exception. I want the exception to
  // break what I'm doing here and propagate to the caller.
  return true;
} finally { 
    // clean up, even if about to propagate the exception 
}

How do you rewrite this? Without code duplication, impossible.

like image 102
Marko Topolnik Avatar answered Sep 29 '22 02:09

Marko Topolnik