Funny try/catch/finally

Posted Thu, 04 Nov 2004

So I ran across an article not too long ago, can't remember where, it was one of those things that just gets passed around, about the importance of try/catch/finally... and how the finally block is executed no matter how the controlling block is terminated. So I put together a toy example to test something out, and thought it was a little cool. Consider the following java method:

public boolean trytest( final int x ) {
     switch( x ) {
          case 0:
               try { return true; }
               finally { break; }
          default:
               return true;
     }
     return false;
}

Now if you were to call this method and pass it 0, what would happen is the try block would return true. Since the controlling block exited, the finally block is hit and the break statement executes, dropping control out of the switch statement so that the return false line statement is executed. The method returns false.

So there ya go. Be careful what you do in your finally's; you can easily override the behavios of your try if you're not paying attention.

Related Books

Cocoa(R) Programming for Mac(R) OS X (3rd Edition) Effective Java (2nd Edition) (The Java Series) C Programming Language (2nd Edition) (Prentice Hall Software) Head First Java, 2nd Edition Programming Interviews Exposed: Secrets to Landing Your Next Job (Programmer to Programmer)

Post a Comment




About

My name is Tim Fanelli, I am a software engineer in Northern NY. I spend most of my time working, and when I can, I try to post interesting things here.

Cigar Dossiers