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 ).