Exception handling in java using finally

public class CheckProg { public int math(int i) { try { int result = i / 0; // throw new IOException("in here"); } catch (Exception e) { return 10; } finally { return 11; } } public static void main(String[] args) { CheckProg c1 = new CheckProg(); int res = c1.math(10); System.out.println("Output :" + res); } 

Question: If I run the above code, I get the result as Output: 11

Why? Shouldn't an exception be thrown in the catch block and returned?

+5
source share
5 answers

Shouldn't an exception be thrown in the catch block and returned?

It is captured, and this return statement is executed ... but then the return value is effectively replaced by the return statement in the finally block, which will execute if there was an exception.

For more information on features, see JLS 14.20.2 . In your case, this is the way:

If the execution of the try block ends abruptly due to a throw of the value of V, then there is a choice:

  • If the run-time type V is an assignment compatible with the perceptible exception class of any catch clause from the try statement, then the first (leftmost) catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and a block of this catch condition is executed. Then there is a choice:

    • If the catch lock completes normally [... is ignored because it is not)

    • If the catch block terminates abruptly for reason R, then the finally block is executed. Then there is a choice:

      • If the finally block completes normally [... is ignored because it does not work]

      • If the finally block completes abruptly for mind S, then the try statement terminates abruptly for reason S (and reason R is discarded).

So, the main line is important - the โ€œreason Sโ€ (in our case, returning the value 11) ends with the try ending abruptly.

+7
source

Yes. But the final block is always executed afterwards and overrides the return value!

+1
source

Finally, the block executes if an exception occurs.

0
source

This is pretty much self-evident. Capture is blocked because there is an exception. Finally, execution will be executed since its execution is guaranteed regardless of the exception.

Note. If you specified some other statements instead of returning, both statements were executed . but in case of a refund, only the last refund is made.

 } catch (Exception e) { System.out.println("10"); } finally { System.out.println("11"); } 
0
source

The finally keyword is used to create a block of code following a try block. The end of the code is always executed, regardless of whether an exception has occurred.

try {

 final int x=100; System.out.println("The value of x is"+ x); 

}

 catch(Exception e) { System.out.println(e); } finally { System.out.println("Finally Block executed"); } 
0
source

All Articles