跳转至

Java 异常处理

异常丢失#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class LostException {
    public static void f() throws ImportException {
        throw new ImportException("重要的异常");
    }

    public static void g() throws CommonException {
         throw new CommonException();
    }

    public static void main(String[] args) {
        try{
            try{
                f();
            }finally {
                g();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}

这里我们会丢失 ImportException的catch

正确的处理方法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class LostException {
    public static void f() throws ImportException {
        throw new ImportException("重要的异常");
    }

    public static void g() throws CommonException {
         throw new CommonException();
    }

    public static void main(String[] args) {
        try{
            try{
                f();
            }catch(Exception e) {
                e.printStackTrace();
            }finally {
                g();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}