The mystery of the anomaly

Source: Internet
Author: User
Tags finally block

Watch several program fragments, analyze the behavior

1.

<pre name= "code" class= "java" ><span style= "font-size:18px;" >public static Boolean fun () {Try{return false;} Finally{return true;}} System.out.println (Fun ());</span>

2.

<span style= "FONT-SIZE:18PX;" >public static Boolean fun () {Try{return false;} Finally{system.out.println ("finally");}} System.out.println (Fun ());</span>

3.

<span style= "FONT-SIZE:18PX;" >public static void Fun () {try{system.out.println ("try"); System.exit (0);} Finally{system.out.println ("finally");}} Fun ();</span>

Results:

1. True

2. Finally

False

3. Try

You can see that the combination of return,finally,exit will have different situations and analyze when the finally block occurs.

In a try-finally statement, the finally statement block always takes control when it leaves the try statement block, regardless of whether the try statement block ends normally or ends unexpectedly.

Unexpected situation:

1. Throw an exception

2, closed statements executed the Break,continue

3. Return appears

So does exit count? It should count, after all, it prevents the program from executing in sequence.

Actually, it's not. Because the exit method will stop the current thread and all other on-the-spot threads, that is, exit directly to the try-finally execution environment is extinguished, not to mention the implementation of the right to finally.

The mystery of the anomaly

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.