Java之finally用来做什么?

我们知道,如果某个程序语言没有垃圾回收和析构函数自动调用机制的话,此时finally就显得十分important。

但是对于Java来说,它有垃圾回收机制,内存释放不再是问题;而且Java中没有析构函数可调用,那么Java在什么情况下会用finally呢?

finally在Java中的用处?

如果要将除内存之外的资源恢复到它们的初始状态,这就需要finally子句。这些需要清理的资源包括了:

已经打开的文件或者网络连接,在屏幕上的图形,甚至我们说是外部世界的某个开关。

用例子来演示?

这段程序的目的是要保证main()函数结束的时候,开关必须是关闭的,所以这种方式下,我们在每个try块和异常处理程序的末尾都加入了对sw.off()方法的调用。

但是在异常被抛出,但没被处理程序捕获,这是这个方法就不会被调用。

public class Switch {
	private boolean state = false;
	public boolean read() {
		return state;
	}
	public void on() {
		state = true;
		System.out.println(this);
	}
	public void off() {
		state =  false;
		System.out.println(this);
	}
    public String toString() {
    	return state ? "on":"off";
    }
}
public class OnOffException1 extends Exception{
	
}
public class OnOffException2 extends Exception{

}
public class OnOffSwitch {
	private static Switch sw = new Switch();
	public static void f()
	throws OnOffException1,OnOffException2{}
	public static void main(String[] args) {
		try {
			sw.on();
			// Code that can throw exceptions...
			f();
			sw.off();
		}catch(OnOffException1 e) {
			System.out.println("OnOffException1");
			sw.off();
		}catch(OnOffException2 e) {
			System.out.println("OnOffException2");
			sw.off();
		}
	}
}

运行结果:

为解决上述问题,使用finally进行改进:

这就保证了sw.f()方法在任何情况下都会被执行。

public class OnOffSwitch {
	private static Switch sw = new Switch();
	public static void f()
	throws OnOffException1,OnOffException2{}
	public static void main(String[] args) {
		try {
			sw.on();
			// Code that can throw exceptions...
			OnOffSwitch.f();
		}catch(OnOffException1 e) {
			System.out.println("OnOffException1");
		}catch(OnOffException2 e) {
			System.out.println("OnOffException2");
		}finally {
			sw.off();
		}
	}
}

甚至于说:在异常没有被当前的异常处理程序捕获的情况下,异常处理机制也会在跳到更高一层的异常处理程序之前,执行finally子句:

在这种情况下,当涉及break和continue语句的时候,finally子句也会执行;但是需要注意的是:

如果我们将finally和带标签的break及continue配合使用,在Java中就没有必要使用goto语句了。

class FourException extends Exception{}

public class AlwaysFinally {

	public static void main(String[] args) {
		System.out.println("Entering first try block");
		try {
			System.out.println("Entering second try block");
			try{
				throw new FourException();
			}finally{
				System.out.println("finally in 2nd try block");
			}
		}catch(FourException e) {
			System.out.println("Caught FourException in 1st try block");
		}finally {
			System.out.println("finally in 1st try block");
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41026809/article/details/92579748