2

I am trying to understand what happens to the exception thrown in try block, when an exception occurs again in finally block?

After running code below, I only see exception thrown in finally block. I am trying to understand what happens to the exception in thrown in try block?

        try{
            int i = 10/0;
        }
        finally {
                System.out.println("one");

                int[] a = new int[2];
                a[4] = 0;

                System.out.println("two");
        }
sammy
  • 31
  • 3
  • finally shouldn't have any exception-prone code. It needs to *finalize* the code block, if anything goes wrong. I.E. closing files, connections and so on. The error will be thrown inside the `finally` if it has one. – Abbas Akhundov Jan 28 '21 at 14:10
  • 1
    related: https://stackoverflow.com/questions/28861617/adding-return-in-finally-hides-the-exception – jaco0646 Jan 28 '21 at 14:11
  • Also, you don't see exception in the try block, but it happens nevertheless. It is simply not shown to you, because you were supposed to handle the exception yourself in `finally` – Abbas Akhundov Jan 28 '21 at 14:11

1 Answers1

1

The exception in the try block gets discarded and forgotten, as specified in the language specification:

  • If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:

....

  • If the run-time type of V is not assignment compatible with a catchable exception class of any catch clause of the try statement, then the finally block is executed. Then there is a choice:
  • If the finally block completes normally, then the try statement completes abruptly because of a throw of the value V.
  • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and the throw of value V is discarded and forgotten).
M A
  • 71,713
  • 13
  • 134
  • 174