If a return statement exists in a try and catch, will the statement in the finally be executed, and what effect does it have on the result? I've written an example to test the problem:
Public StaticMap<string, string>Getmaptry () {Map<string, string> map =NewHashmap<string, string>(); Map.put ("KEY", "INIT"); Try{map.put ("KEY", "TRY"); returnmap; } Catch(Exception e) {map.put ("KEY", "CATCH"); E.printstacktrace (); } finally{map.put ("KEY", "FINALLY"); } System.out.println ("---------End--------"); returnmap; } Public StaticMap<string, string>Getmapcatch () {Map<string, string> map =NULL; Try{map.put ("KEY", "TRY"); } Catch(Exception e) {map=NewHashmap<>(); Map.put ("KEY", "CATCH"); E.printstacktrace (); returnmap; } finally{map.put ("KEY", "FINALLY"); } System.out.println ("---------End--------"); returnmap;} Public Static intgetInt () {Map<string, string> map =NULL; intRET =0; Try{map.put ("KEY", "TRY"); RET= 1; } Catch(Exception e) {map=NewHashmap<>(); Map.put ("KEY", "CATCH"); E.printstacktrace (); returnret; } finally{map.put ("KEY", "FINALLY"); RET=3; } System.out.println ("---------End--------"); returnret; } Public Static voidMain (string[] args) {System.out.println ("Try:" + getmaptry (). Get ("KEY"). toString ()); System.out.println ("Catch:" + Getmapcatch (). Get ("KEY"). toString ()); System.out.println ("Int:" +getInt ()); }
Execution Result:
Try:finally
Java.lang.NullPointerException
At Com.wmshua.test.FinallyReturnRelation.getMapCatch (finallyreturnrelation.java:43)
At Com.wmshua.test.FinallyReturnRelation.main (finallyreturnrelation.java:14)
Catch:finally
Java.lang.NullPointerException
At Com.wmshua.test.FinallyReturnRelation.getInt (finallyreturnrelation.java:63)
At Com.wmshua.test.FinallyReturnRelation.main (finallyreturnrelation.java:15)
int:0
Results Analysis:
The reference type has changed and the base data type has not been modified.
The following conclusions are drawn from the implementation results:
- Finally executes even if there is a return in a try or catch and execution occurs.
- Finally, the modification of the variable occurs before the end of the method call.
- The return statement is executed before finally.
- Return returns the result of not returning the original data but copying the original data, copying the base type value, referencing the type copy reference, and not copying the value within the reference.
- The in-finally statement can affect the reference type without affecting the base data type.
Java Small knowledge point-finally and return execution relationship