异常丢失

Posted by Eric Jin on 2018-12-23

Error handing with Exceptions

java 中的异常处理有两种情况会使异常丢失

  1. try-finnaly 使用
public class LostMessage {

    public static void main(String[] args) {
        try {
            LostMessage lm = new LostMessage();
            try {
                lm.f();     //ImportantException被抛出,直接进入finally
            } finally {
                lm.dispose();   //finally 中抛出HohunException,ImportantException 异常信息会丢失
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

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

try 后面直接跟 finally,如果 finally 中抛出另一个异常,try 中抛出的异常就丢失了。

  1. 一种更简单的方式:try-finally 直接 return
public static void main(String[] args) {
    try {
        LostMessage lm = new LostMessage();
        try {
            lm.f();
        } finally {
            return;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

f() 中抛出的异常也丢失了。