Java之异常丢失

当然,Java中也存在瑕疵的地方。异常作为程序出错的标志,绝不应该被忽略,但它还是有可能被轻易忽略。

用某些特殊的方式使用finally子句,就会发生这种情况:

class VeryImportantException extends Exception{
	public String toString() {
		return "A very important exception";
	}
}
class HoHumException extends Exception{
	public String toString() {
		return "A trivial exception";
	}
}
public class LostMessage {
	void f() throws VeryImportantException{
		throw new VeryImportantException();
	}
	void dispose() throws HoHumException{
		throw new HoHumException();
	}

	public static void main(String[] args) {
		try {
			LostMessage lm = new LostMessage();
			try {
				lm.f();
			}finally {
				lm.dispose();
			}
		}catch(Exception e) {
			System.out.println(e);
		}
	}
}

输出结果:

从输出的结果中,我们可以看到:VeryImportantException不见了,它被finally子句里的HoHumException所取代。

这是十分严重的缺陷,因为异常可能会以一种比前面例子所示的更加微妙和难以觉察的方式丢失。

一种更加简单的丢失异常的方式,是从finally子句中返回:

这个程序运行之后,我们可以看到既使抛出了异常,它也不会产生任何输出。

public class ExceptionSilencer {

	public static void main(String[] args) {
		try {
			throw new RuntimeException();
		}finally {
			return;
		}
	}
}

谢谢大家!

猜你喜欢

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