So for example if we have try-catch
like this:
try {
readDataFromTable("EMPLOYEES");
} catch (Exception e) {
e.printStackTrace();
}
Are there some circumstances where finally
block is needed?
So for example if we have try-catch
like this:
try {
readDataFromTable("EMPLOYEES");
} catch (Exception e) {
e.printStackTrace();
}
Are there some circumstances where finally
block is needed?
Are there some circumstances where
finally
block is needed?
Yes there are:
The finally
block is also executed in the event of a return
, continue
or break
that ends the try
block, an exception thrown in the catch
block, and so on.
There are exceptions that won't be caught by catch (Exception e) {
. (And that you shouldn't catch them. They are Error
and its subclasses.)
(Just about the only thing that won't run the code in a finally
block is an action that causes the JVM to exit.)
Note that you shouldn't write code like that anyway. It is usually a bad idea to try to handle Exception
, because it is typically too difficult to figure out all of the possible exceptions that could occur ... and hence what to do about it. (Printing a stacktrace and continuing is rarely the correct thing to do!)
That means the idea of "handling all of the exceptions" instead of a finally
is typically impractical.
finally
defines block that will be always executed - no matter whether exception was thrown or not
So it's up to your business logic do you need to perform such action or not
You can find detailed description and example in the official documentation