In a Java method, after a return in a try, the later finally executes?
The test code is as follows:
publicintprint(){ try { System.out.println("try"); return1; } catch(Exception e){ return0; } finally{ System.out.println("finally"); } }
See the results directly:
Try
Finally
Reason:
The finally statement executes before the return.
What if we add a return to finally?
The test code is as follows:
Public classMain { 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 results are as follows:
Try
Finally
2
Deep Understanding:
An analysis of the depth of the finally statement block in Java
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Does Java return after a try and finally does not execute?