1.
Packagecn.day006; Public classTest { Public Static voidMain (string[] args) {System.out.println (GetResult ()); } @SuppressWarnings ("Finally") Public Static intGetResult () {intA =100; Try{ returna+1;//Note that the underlying data type of Java is value passing, and the return value here is not related to the A above .}Catch(Exception e) {e.printstacktrace (); }finally{ returnA//finally redirect the value to a (equivalent to overwriting the return value in the try), so the output is } }}
Results: 100
2.
Package cn.day006; Public classTest { Public Static voidMain (string[] args) {System. out. println (GetResult ()); } @SuppressWarnings ("finally") Public Static intGetResult () {intA = -; Try{ returna++;//remember a++----> a=a+1 The value of a at this time has changed}Catch(Exception e) {e.printstacktrace (); }finally{ returnA; } }}
Results: 101
3.
Packagecn.day006; Public classTest { Public Static voidMain (string[] args) {System.out.println (GetResult ()); } Public Static intGetResult () {intA =100; Try{
a++; returnA; }finally{ a++; } }}
The result is 101.
Analysis:
In a try statement, when the return statement is executed, the result to be returned is ready, at which point the program goes to finally executes.
Before you go, try to store the result to be returned in a different local variable from the X, and after the finally is executed, the returned result is removed from it.
Therefore, even if the variable x is changed in Finally, it does not affect the return result.
It should use the stack to hold the return value.
4.
Package cn.day006; Public classTest2 { Public Static voidMain (string[] args) {Try{System. out. println (GetResult ()); }Catch(Exception e) {e.printstacktrace (); System. out. println ("Intercept Exception Catch"); }finally{System. out. println ("Exception Handling finally"); }} @SuppressWarnings ("finally") Public Static intGetResult () throws exception{intA = -; Try{a=a+Ten; Throw Newruntimeexception (); }Catch(Exception e) {System. out. println ("intercept exceptions and re-throw exceptions"); Throw NewException (); }finally{ returnA; } }}
The results are as follows:
Intercept exceptions and re-throw exceptions
110
Exception handling finally
The key "intercept exception catch" did not execute!!!
The reason is to return a value in the finally of GetResult (), the equivalent of telling the compiler that the method has no exception, but in fact the exception is there, the result is that the caller of the method is not caught by the exception, relative to the exception was eaten by the unprovoked, hidden murderous ah!!
Reference Cow Blog: http://www.cnblogs.com/Fskjb/archive/2012/02/15/2353256.html
Handling Exceptions in Java return keyword