0

let's consider the following code:

try {
    throw new Exception("from try")
} catch (Exception e) {
    throw new Exception("from catch")
} finally {
    throw new Exception("from finally")
}

It gives:

Exception thrown
java.lang.Exception: from finally
<...>

So it looks that finally is executed before catch and terminates execution flow.

What could I do if want to see both exceptions?

MaratC
  • 6,418
  • 2
  • 20
  • 27
Igor A
  • 311
  • 3
  • 10
  • You can't throw *two* times in a method. If you throw on the `finally` cause, the throw statement from the catch() block won't execute. On the other hand, (obviously) if you use System.out.println(..), you will see all messages – Daniele Mar 24 '20 at 08:29
  • Not sure on your actual problem though. If you perform some cleanup in the `catch` block and the cleanup code can throw, you could use nested: `.. catch { try {..} catch{..}}` – Daniele Mar 24 '20 at 08:31
  • In `Java` `Finally` block is always Executed you cannot throw exception two times in a method. Try block are handled in`catch` exception. – kedar sedai Mar 24 '20 at 08:32
  • The problem is with exceptions from the underlying library. I have a resource creation in *try* block and cleanup in *finally* block. Cleanup fails with an exception when a resource was not created, and the exception for resource creation is hidden by the exception in *finally*, so I can not find what was wrong. – Igor A Mar 24 '20 at 09:23

2 Answers2

1

So it looks that finally is executed before catch and terminates execution flow.

That is not correct. finally is executed after a correspondeing catch, not before. The issue is that your catch block executes, and then after that the finally block is guaranteed to execute.

Jeff Scott Brown
  • 26,804
  • 2
  • 30
  • 47
  • I think in addition to this, you can get at the exception thrown from the catch block in the suppressed exceptions of the exception thrown from the finally block. – emilles Mar 25 '20 at 03:38
  • @emilles - I don't think there would be any suppressed exceptions in the scenario described in the original question. Am I mistaken about that? – Jeff Scott Brown Mar 25 '20 at 13:40
  • I tried this in the debugger and no suppressed exceptions are available. So no easy way to get to exception thrown from catch block. – emilles Mar 26 '20 at 16:14
0

This post will help you I guess:

https://stackoverflow.com/questions/3779285/exception-thrown-in-catch-and-finally-clause
Abhishek Kulkarni
  • 1,747
  • 1
  • 6
  • 8