After return in try, does Java still execute finally ?, Returnfinally
In the Java method, after return in try, will the finally be executed?
The test code is as follows:
public int print(){ try { System.out.println("try"); return 1; } catch(Exception e){ return 0; } finally{ System.out.println("finally"); } }
View the result directly:
Try
Finally
Cause:
The finally statement is executed before return.
What if I add a return in finally?
The test code is as follows:
public class Main { public static void main(String[] args) { System.out.println(print()); } public static int print(){ try { System.out.println("try"); return 1; } catch(Exception e){ return 0; } finally{ System.out.println("finally"); return 2; } }}
The result is as follows:
Try
Finally
2
In-depth understanding:
In-depth analysis of finally statement blocks in Java
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.