There is a return statement in try {}, so the code in finally {} following this try will not be executed. When will it be executed, before or after return ?,

Source: Internet
Author: User

There is a return statement in try {}, so the code in finally {} following this try will not be executed. When will it be executed, before or after return ?,

This is an interview question. First, the code in finally {} will certainly be executed. As for whether it is before or after return,

According to the answer, it is executed after return. I don't think so. Baidu has a bit of it. Some say that it is before return, some say it is after return, and some execute in the middle of return. Then a small test is performed as follows:

Static void Main (string [] args) {// Test (); System. console. writeLine ("ended"); System. console. readLine () ;}/// <summary> /// Test /// </summary> /// <returns> </returns> private static int Test () {try {System. console. writeLine ("Good, start"); return ReturnInt () ;}catch (Exception exception Exception) {System. console. writeLine ("I am an exception"); throw;} finally {System. console. writeLine ("I am finally ");}} /// <summary> /// return number /// </summary> /// <returns> </returns> private static int ReturnInt () {System. console. writeLine ("I am return"); return 1 ;}

The test results are as follows:

So I think the code in finally {} is executed after return.

This test is rough. If you have other methods to prove it, please advise.

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.