首页 > 解决方案 > 尝试在 Java 中两次处理异常

问题描述

我正在尝试处理异常 2 次

第一个是定义方法的核心:

Class Class1 {
    public int method (int a, String b) {
    try {
        System.out.println(a+"  "+b.length());
    }
    catch (NullPointerException e) {
        // TODO: handle exception
        System.out.println("catch from the method");
    }
    finally {
        System.out.println("finally from the method");
    }   
    return 0;
    }
}          

第二个

当我在 main 中调用此方法并将 null 参数传递给它时:

public Class Class2 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Class1 c = null;
        try {
            c = new Class1();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            c.method(1, null);
        }
        catch (Exception e) {
            // TODO: handle exception
            System.out.println("catch from the main");
        }
        finally {
            System.out.println("finally from the main");
        }
        System.out.println("\nEnd of the main");
    }
}        

结果是:

从方法中捕获

最后从方法

终于从主

主线结束

现在我的问题是,为什么 main 中的 catch 块没有被执行?

标签: java

解决方案


一旦你捕捉到一个异常,它就不会再进一步​​了,但你可以再次抛出它。如果您希望您的 main 也看到异常,则需要在捕获异常后再次抛出异常。尝试这个:

 public int method (int a, String b) throws NullPointerException{
        try {
            System.out.println(a+"  "+b.length());
        }
        catch (NullPointerException e) {
            // TODO: handle exception
            System.out.println("catch from the method");
            throw e;
        }
        finally {
            System.out.println("finally from the method");
        }   
        return 0;
        }

请注意,由于现在函数中有一个 throw,您需要将其包含在函数定义中

编辑:正如几个人所说,NullPointerException 并不真正需要被捕获,因为它是一个未经检查的异常。这是因为它是 RuntimeException 的子类。


推荐阅读