Home > Enterprise >  Try-finally with lock when no exception is thrown
Try-finally with lock when no exception is thrown

Time:10-01

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();
}

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

Adding it always is a reasonable advice:

  • For a beginner, because they may not be aware of all the ways exceptions might be thrown.
  • For more experienced devolpers, because it avoids forgetting to add it later, and, as Andy Turner correctly points out in another answer, it comes essentially without cost.

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.

  • Related