Java Exception Handling: Do not return in finally

Source: Internet
Author: User

 

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 !!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.