In java, what if you try and catch throwing the same exception and finally return?

public class Abc { public static void main(String args[]) { System.out.println(Abc.method()); } static int method() { try { throw new Exception(); } catch(Exception e) { throw new Exception(); } finally { return 4; } } } 

Why is the return value 4?

+4
source share
5 answers

How finally works. Fragment

 try { throw new Exception(); } catch(Exception e) { throw new Exception(); } 

will end abruptly, but the finally clause takes effect, and when it returns, it cancels the original reason for the completion of the statement.

This is explained in the Blocks and Expressions section of the Java Language Specification. I highlighted the appropriate path in your situation:

A try with The finally block is executed by first executing a try . Then there is a choice:

  • If the execution of the try block completes normally, then the finally block is executed, and then there is a choice:
    • ...
  • If the execution of the try block suddenly terminates due to the throw value V , then there is a choice:
    • If the run-time type V is equal to that assigned to the parameter of any catch try , then the first (leftmost) one is catch . A catch clause is catch . The value V is assigned to the parameter of the selected catch , and the block of this is met. The catch condition is met. Then there is a choice:
      • If the catch completes normally, the finally block is executed. Then there is a choice:
        • ...
      • If the catch terminates abruptly due to R , then the finally block is executed. Then there is a choice:
        • If finally completes completion normally, try automatically terminates Cause R.
        • If the finally block terminates abruptly for reason S , then try automatically ends reason S (and reason R is discarded).
    • If the run-time type of V is not assigned to any catch try clause, then the finally block is executed. Then there is a choice:
      • ...
  • If the execution of the try block terminates abruptly for any other reason R , then the finally block is executed. Then there is a choice:
    • ...
+14
source

You should never return from a finally block. This is a very bad practice. See Java's try-finally return design question and Is it finally running in Java? .

+2
source

There are several questions in StakOverflow that explain this.

To make it simple: if you put a return or throw statement in a finally clause, this is the last action of your method. Generally speaking, this is bad practice.

+1
source

Finally, 4. will always be returned. The finally block will always be executed regardless of any exception that throws try and catch.

+1
source

The fact that the finally block returns a value causes a missed exception, so it will not propagate outside the method.

0
source

Source: https://habr.com/ru/post/1341415/


All Articles