Public Class Ex1 {
Public Static VoidMain (string [] ARGs ){
System. Out. println (ex1.getresult ());
}
Public Static Int Getresult (){
Int A = 100;
Try {
Return A + 10; // Note that the basic data type of Java is value passing, and the returned value has nothing to do with a above.
} Catch (Exception e) {e. printstacktrace ();
}Finally {
Return A; // Finally, redirect the value to a (equivalent to overwriting the return value in try), so the output is still 100
}
}
}
Let's look at another example:
Public Class Ex1 {
Public static void main (string [] ARGs) {
try {
system. out. println (ex1.getresult ();
}< span style = "color: # 0000ff"> catch (exception e) {
E. printstacktrace ();
system. out. println ("catch exceptions");
}< span style = "color: # 0000ff"> finally {< br> system. out. println ("Exception Handling finally");
}< BR >}
Public Static Int Getresult () Throws Exception {
Int A = 100;
Try {
A = a + 10;
Throw New Runtimeexception ();
} Catch (Exception e ){
System. Out. println ("intercept exceptions and throw exceptions again ");
Throw New Exception ();
}Finally {
Return A;
}
}
}
The output is as follows:
Intercept exceptions and throw exceptions again
110
Exception Handling finally
The key "catch exception" was not executed !!!
The reason is that return a value in finally of getresult (), which is equivalent to telling the compiler that the method has no exception, but actually there are some exceptions, the result is that the caller of this method cannot catch the exception, and the exception is swallowed up without reason, hiding the machine !!
Conclusion: do not try to return a value in finally. This may lead to unexpected logic errors. Finally is used to release resources !!