|
-
December 4th, 2008, 05:39 PM
#1
Clarification regarding finally blocks
I'm primarily a C++ programmer who has to work with Java code now and then. I'd like some clarification regarding when finally blocks will be executed.
Let's say I lock a mutex. Or Lock, as Java prefers to call the things. Anyway, I want to ensure that when the function exits the thing is unlocked, without having "unlock()" calls scattered through every catch block and at every return statement. (Let's say I didn't write this code and wouldn't have used so many return statements if I had.)
Can I just stick a finally block at the end of the function, and assume that it will be called no matter where the function returns from or what exceptions get thrown? Or does it have to follow a try block? Let's say:
Code:
lock.lock();
try {}
catch {
return;
}
try {}
catch{}
catch{}
finally{
lock.unlock();
}
will the finally apply even if there's a return statement in the first catch, which is part of a different try/catch structure?
In C++ I'd just put a scoped mutex lock on the stack and be done with it, but I'd like to learn the right way of doing it in Java.
Last edited by Lindley; December 4th, 2008 at 05:51 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|