ITeye博客

finally 语句的妙用2

wangyun · 2008-06-05 21:48 · Java · Markdown

虽然标题说是finally 语句的妙用,但其实是finally 的错误用法。我们在编写的时候应该时刻的避免这种情况的发生!

言归正传,finally 语句的这个妙用的用途是丢失异常。

代码如下: class VeryImportantException extends Exception {

}

class HoHumException extends Exception {

}

public class LostMessage {

void f()throws VeryImportantException {
	throw new VeryImportantException();
}

void dispose()throws HoHumException {
	throw new HoHumException();
}

/**
 * @param args
 */
public static void main(String args)throws Exception {
	// TODO Auto-generated method stub
	LostMessage lm = new LostMessage();
	try {
		lm.f();
	}finally {
		lm.dispose();	//VeryImportantException异常将被丢失
	}
}

}

通过这个简单的例子,我们应该小心处理finally 块中的代码,避免发生这类事情的发生。尽可能不要在finally 块中抛出错误的异常。导致之前异常的丢失!

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。