Skip to content
Advertisement

Try-finally with lock when no exception is thrown

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement