1. There are at least two scenarios in which the finally statement is not executed:
(1) The Try statement is not executed, such as return before the try statement , so that the finally statement does not execute , This also shows that the necessary rather than sufficient condition for the finally statement to be executed is that the corresponding try statement must be executed.
(2) There is system.exit (0) in the try block, such a statement, System.exit (0), terminates the Java Virtual Machine JVM, even the JVM is stopped, all is finished, and the finally statement is not executed.
-->1. The case is as follows:
1 PackageCom.himi.finallydemo;2 3 Public classFinallyDemo2 {4 5 Public Static voidMain (string[] args) {6 System.out.println (GetInt ());7 8 }9 Ten Public Static intgetInt () { One intA = 10; A Try { -System.exit (0); -System.out.println (a/0); theA = 20; - -}Catch(ArithmeticException e) { -A = 30; + //return A; -}finally { +A = 40; A } at - returnA; - } - -}
The results are as follows:
In the Getint () method above, an int a = 10 is executed first, then the try statement is executed, and the start is System.exit (0), so that the VM JVM exits directly and does not print any information at random.
-->2. The cases are as follows:
1 PackageCom.himi.finallydemo;2 3 Public classFinallyDemo2 {4 5 Public Static voidMain (string[] args) {6 System.out.println (GetInt ());7 8 }9 Ten Public Static intgetInt () { One intA = 10; A Try { -System.out.println (a/0); //execute, jump directly to line 17th -System.exit (0); theA = 20; - -}Catch(ArithmeticException e) { -A = 30; + //return A; -}finally { +A = 40; A } at - returnA; - } - -}
Run the following effect:
This is done in the try statement. System.out.println (a/0), the system immediately catches an exception to execute the Catch statement, executes the finally statement, and finally return a
(At this point A is 40)
-->3. Case:
1 PackageCom.himi.finallydemo;2 3 Public classFinallyDemo2 {4 5 Public Static voidMain (string[] args) {6 System.out.println (GetInt ());7 8 }9 Ten Public Static intgetInt () { One intA = 10; A Try { -System.out.println (a/0); -System.exit (0); theA = 20; - -}Catch(ArithmeticException e) { -A = 30; + returnA; - /* + * Return a when the program executes to this step, this is not return a but return 30; The return path is formed. A * But, it found that there is finally, so continue to execute the contents of fianlly, a=40 at * Go back to the previous return path again and continue to return; - */ -}finally { -A = 40; - //return;//If that turns out to be - } in - returnA; to } + -}
The results are as follows:
Java Fundamentals Hardening IO Stream Note 06: If there is a return before finally, the question of the face