Thursday, September 27, 2007

Java 'finally'

I have learned about a feature of Java that interests me. Actually, according to this web page, it's one of the shameful things about Java:

In a try/finally block, the finally code really is called in all situations. That's good, because we want to be able to do some in all cases clean-up code a lot of the times. But what happens if you 'intercept' normal control flow? For instance, the code inside the try block wants to return, but we don't let it? Turns out, this code will not return.

void foo() {
  while(true) {
    try {
      return;
    } finally {
      continue;
} } }


While this seems a little bit wild, it's actually really helpful for my current project. You see we're translating some new programming constructs into straight-up Java. The problem is, a user could call return in his code when, according to the semantics of our new features, the method shouldn't return. In summary, I was glad that this was the case, because it lets met avoid some gnarly rewriting of the input code.

1 comment:

  1. That behavior doesn't actually phase me at all, and any other behavior (other than disallowing "return" within try-catch-finally altogether) would be, I imagine, worse. I won't get started on my problems with the idea of a "Principle of Least Astonishment."

    If you write the program so that the last thing a procedure does is return, and it can only do it in one place, then this stops being so confusing. Integrating these new-fangled (try-catch-finally) and old-fangled (return-in-the-middle) features - they seem like quite different visions of control flow, and so no one should be the least bit astonished (heh, heh) if they produce counterintuitive behavior.

    ReplyDelete