How exactly did you get that "finally block does not complete normally" warning? I added some declarations to your code, and got the followingm which compiled just fine:
But I definitely don't recommend this coding style. Here's why:
1) This code catches runtime exceptions. That's an inefficient way to check preconditions.
2) "Handling of the finally block is rather complex." That's a direct quote from the
Java Language Spec. Now if
I think something's complex, that might not mean much, but if
Gosling thinks it's complex, then it's definitely complex. If you use a finally block when a simple return statement will do, you introduce mystery and complexity. Those are good things when you're writing a story
but it's best to avoid them in your code.
So what's
good for? What value does it add? If all exceptions raised in the try and catch blocks are handled by the catch blocks, then a finally block adds no value. The value comes in when an exception is handled by the current method's caller, or some higher level of the calling sequence. In this case the finally block executes before the exception is handled by the higher level. Here's a simple example:
The output is:
thrower() finally
test() caught IOException
You would get the same result if test() had some catch blocks for exception types other than IOException.
If you're not in this kind of situation (Exceptions handled outside of the current method), there's no value to the catch block.
There's an animated illustration of the try/catch mechanism in Chapter 11 of "Ground-Up Java". But I decided not to include the finally mechanism because I didn't want to overwhelm people.