0

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?

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
milos
  • 77
  • 3
  • 10
  • 2
    Catching `Exception` (which is not a good idea generally, by the way) and having a `finally` block are completely orthogonal to each other, i.e. one doesn't affect the other. – Federico klez Culloca May 14 '21 at 09:41
  • 1
    There are other ways that can interrupt the program flow. There is also Throwable and Error. finally block should be used when there is an action you absolutely must take. Like releasing a lock. The autoclosable feature has made it a bit less useful. – matt May 14 '21 at 09:44
  • why is my question duplicate? I know the answer for provided question – milos May 14 '21 at 11:24

2 Answers2

1

Are there some circumstances where finally block is needed?

Yes there are:

  1. 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.

  2. 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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

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

m.antkowicz
  • 13,268
  • 18
  • 37