Java's execution will finally clause

In the exception handling process, sometimes we want regardless of whether the try block throws an exception, all of them can be implemented. This usually applies to situations other than memory recovery.

To achieve this effect, it can be added after the finally clause exception handler.

The following program demonstrates finally clause is always able to run:

class ThreeException extends Exception{}

public class FinallyWorks {
	static int count = 0;

	public static void main(String[] args) {
		while(true) {
			try {
				// Post-increment is zero first time:
				if(count++ == 0)
					throw new ThreeException();
				System.out.println("No exception");
			}catch(ThreeException e) {
				System.out.println("ThreeException");
			}finally {
				System.out.println("In finally clause");
				if(count == 2)break; // out of while
			}
		}
	}
}

operation result:

We can see this program, regardless of whether an exception is thrown, finally clause always be executed.

 

Guess you like

Origin blog.csdn.net/qq_41026809/article/details/92574185