Why use finally instead of code after catch [duplicate]
Solution 1:
Because if an exception gets thrown no code after the try
block is executed unless the exception is caught. A finally
block is always executed no matter what happens inside your try
block.
Solution 2:
Look at your catch block - it's going to throw DAOException
. So the statements after your catch block aren't going to be executed even in the sample you've given. What you've shown (wrapping one exception in another) is one common pattern - but another possibility is that the catch block "accidentally" throws an exception, e.g. because one of the calls it makes fails.
Additionally, there may be other exceptions you don't catch - either because you've declared that the method throws them, or because they're unchecked exceptions. Do you really want to leak resources because an IllegalArgumentException
got thrown somewhere?