Conclusion : The finally statement is executed before any return statement in a try or catch is executed, if finally exists.
If there is a return statement in Finally, then the program will return, so the return in the finally is bound to return,
The compiler implements the return in finally as a warning.
It should be noted, however, that the return statement in try or catch, if return is an int, a long, a double constant type, and a package type of string, integer, etc. Then the change to the value of the return variable in finally does not affect the return result of the return statement in the try or catch.
The opposite is: in a try or catch return statement, if the return is a list, and so on, the value of the object type, then the change in finally will affect the return statement in the try or catch results.
Of course, if you execute the return statement in Finally, finally the change to the return value will affect the return value.
Illustration 1:
public static int Trycatchfinallyreturn () { int a = 1;int b = 100;try{a = 2;return a+b-2;} catch (Exception e) {e.printstacktrace ();} Finally{system.out.println ("finally"); a = 4; System.out.println (a); System.out.println ("Finally2");} return a+b;}
Main method: int c = Trycatchfinallyreturn (); System.out.print (c);
The output is:
finally4finally2100
Note Although the value of a is changed to 4, the return value in the try is not modified.
Illustration 2:
public static list trytest () {list<integer> list = new arraylist<integer> (); int a = 2;try{list.add (new Integer (a)); for (Integer ii:list) {System.out.println (Ii.intvalue () + "----");} return list;} catch (Exception e) {e.printstacktrace ();} Finally{system.out.println ("finally"); a = 4; System.out.println (a); List.add (New Integer (a)); System.out.println ("Finally2"), for (Integer ii:list) {System.out.println (Ii.intvalue () + "----");}} return list;}
Main method:list<integer> A = trytest (), for (Integer b:a) {System.out.println (B.intvalue () + "----main");}
Operation Result:
2----FINALLY4FINALLY22----4----2----MAIN4----main
the description affects the return result of the object type.
Illustration 3:
public static string tryteststring () { string a = "AAA"; String B = "BBB"; try{a = "Aaa2"; return a+b;} catch (Exception e) {e.printstacktrace ();} Finally{system.out.println ("finally"); a = "Aaa3"; System.out.println (a); System.out.println ("Finally2");} return a+b;}
Main method: System.out.println (Tryteststring ());
Output:
finallyaaa3finally2aaa2bbb
is the same as returning the constant result.
Copyright NOTICE: This article is the original blogger article, reproduced please indicate the source: Http://blog.csdn.net/lingzhm
Try Catch finally return