finally Keyword Considerations

Definitions:
a finally as part of exception handling, it can only be in try / catch statement, and comes with a block of statements, the statements represent the final will be executed (with or without throwing an exception), is often used when you need to release in the case of resources. Especially in this regard close the connection, the database if the programmer is connected Close () method in the finally, it will greatly reduce the risk of error.

Precautions:

  • If you try contains System.exit (0), to exit the virtual machine, then finally in the statement is not executed, there is no implementation of the program to try to abort the statement, it will not execute finally, the last one is when all non-daemon when a thread abort, daemon thread whether it exists or not, the virtual machine will kill off the daemon thread thus stop the program. Virtual machine, the main method of execution thread is a non-daemon threads, garbage collection is another daemon thread executing the main, the program suspended, regardless of the garbage collection thread is suspended. So if the finally block exist daemon thread, then when all non-daemon thread abort, kill off a daemon thread, which finally block will not be implemented.

  • try catch finally, there are enforcement mechanisms of return (that try and catch in both return):

    • When finally there is no return, even finally returned in the variable code is modified, but only the scope and finally block behind the code is valid, return of the actual return value or try or catch before. Such as:
public static int test() {
		int i = 0;

		try {
			
			return i ++;
		} catch (Exception e) {
			e.printStackTrace();
			return 1;
		} finally {
			
			i ++;
			System.out.println(i);
//			return i;
		}

	}

public static void main(String[] args) throws CloneNotSupportedException {
		
		System.out.println(test());

	}

It will print 2 and 0. The reason is that will be performed before finally statements / catch general statement executed, including the return operation, in this code, the return i ++ is executed try, but not to return, and the like finally complete execution before returning. But why finally modify the value to be returned does not use it? Should try before returning to the variable i is the i ++ operations after a backup again, i finally back up to operate at this time of the backup operation will naturally not affect the original variable i.

  • When finally there return, return i coming in the above code; deleted notes, the result will be changed to 2 and 2, the reason is, finally has returned, try or catch will not be executed.
Published 14 original articles · won praise 15 · views 526

Guess you like

Origin blog.csdn.net/CodingNO1/article/details/104291120