Reputation: 405
In the java manual it says that it is recommended to use try-finally when using lock() and unlock(), but this is also necessary when an exception is never thrown in the try block? for example:
mutex.lock();
try
{
x++
} finally {
mutex.unlock();
}
Upvotes: 2
Views: 456
Reputation: 6583
Adding it always is a reasonable advice:
If you can prove that there is no way that an exception is thrown, then you don't need the try-catch block.
But you need to remember that you'll have to add it if you later decide to add more code to that section.
Some static code analyzing tools flag not using it as a potential problem - they usually do not try to prove that a certain section of code cannot throw, which would be difficult to do in general.
Upvotes: 1
Reputation: 140484
It's simply good practice to do it always.
Then you don't have to worry about trying to work out whether the code inside the lock does or does not throw (both now and if the code is changed in the future).
Just as a data point, not using try/finally with a lock is flagged in Google's code reviews, irrespective of what you do while holding the lock.
Using try/finally essentially has no cost; but not using it when you need it can be very costly indeed.
Upvotes: 2
Reputation: 139
It's just standard practice. In the future, someone can change that line of code into a function call, which might throw an exception. So it's better to use finally to allow the exception to propagate normally.
Upvotes: 2