虽然标题说是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 块中抛出错误的异常。导致之前异常的丢失!
言归正传,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 块中抛出错误的异常。导致之前异常的丢失!
本文通过一个简单示例展示了在Java中不当使用finally语句可能导致的异常丢失问题,并强调了在finally块中避免抛出新的异常的重要性。
862

被折叠的 条评论
为什么被折叠?



