Try-catch-finally, trycatch

Source: Internet
Author: User
Tags finally block

Try-catch-finally, trycatch

Use the intermediate code to check the essence of try-catch-finally:

Class Program {static void Main (string [] args) {Program p = new Program (); Console. writeLine (p. test1 (); // Console. writeLine (p. test2 (); Console. read () ;}// the result is: 3 private TestClass Test1 () {TestClass tc = new TestClass (); try {tc. testVar = 2; return tc;} catch (Exception) {throw;} finally {tc. testVar = 3 ;}// the result is: 2 private int Test2 () {int test = 1; try {test = 2; return test;} catch (Exception) {throw;} finally {test = 3 ;}} class TestClass {public int testVar = 111; public override string ToString () {return testVar. toString ();}}


When Test1 is called, the intermediate Code assigns only one reference to the local variable, so the finally operation has an impact. The intermediate code is:



When you call return in Test2 and try, the return value is saved in the local variable of the intermediate code, instead of the test variable in the source code. Therefore, the finally operation is invalid. The intermediate code is:



In java, What is the code running sequence of try-catch-finally blocks?

Continue running
Try {
Throwing an exception
} Catch (catch exception ){
Print stack
}
Finally {
It is usually to release resources (for example, if you open a file in try, an exception occurs and it is not closed, it is written in finally like this)

The statements in finally will go regardless of whether the catch statement is executed or not.
}
The following statement runs normally without affecting

Use the try-catch-finally statement structure in the program to handle exceptions

Get an exception from the try block, and then catch the block for processing (usually throws, data rollback, and log writing ), the program in the finally block is the final execution (whether or not the previous program throws an exception ).

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.