JAVA中的链式异常工具

JAVA中的链式异常工具,java,exception,Java,Exception,我可以在java中实现链式异常功能 案例1: public static void main(String[] args) { try { method1(); } catch (Exception e) { System.out.println("Exception in the main method :: "+e); } } private static void method1() throws Exception {

我可以在java中实现链式异常功能

案例1:

public static void main(String[] args) {

    try {
        method1();
    } catch (Exception e) {
        System.out.println("Exception in the main method :: "+e);
    }

}

private static void method1() throws Exception {
    try{
        System.out.println("Inside Try Block"+10/0);
    } catch(ArithmeticException e){
        System.out.println("Exception in method1 :: "+e);
        throw e;
    } finally{
        System.out.println("In FinallY Block");
    }

}
案例2:

public static void main(String[] args) {

    try {
        method1();
    } catch (Exception e) {
        System.out.println("Exception in the main method :: "+e);
    }

}

private static void method1() throws Exception {
    try{
        System.out.println("Inside Try Block"+10/0);
    } catch(ArithmeticException e){
        System.out.println("Exception in method1 :: "+e);
        throw (ArithmeticException)new ArithmeticException().initCause(e);
    } finally{
        System.out.println("In FinallY Block");
    }
}
我得到的结果是

Exception in method1 :: java.lang.ArithmeticException: / by zero
In FinallY Block
Exception in the main method :: java.lang.ArithmeticException: / by zero
我的问题是:

  • 这两种情况有什么区别吗
  • 哪种方法更好
  • 为什么有两个案例是为了同样的目的
  • 不同之处在于,在第二种情况下,您将原始的
    算术异常
    异常包装在另一个相同类型的异常中(请参见下文为什么这是毫无意义的)

  • 案例1可能是您希望在这里使用的,因为您没有扩展异常的含义(到更高的级别)

  • 他们没有相同的目的,让我解释一下

  • 如果将异常设置为原因,则其含义不同。通过将
    算术异常
    包装在更高级别的异常中,可以赋予它更大的含义。在这里,您只是将其包装在另一个
    算术异常中,这是没有意义的


    例如,当您试图从web服务获取一些数据时,您可能需要一个原因:发送HTTP请求的低级方法抛出一些
    SocketException
    HttpException
    ,您将它们包装在一些高级异常中,这些异常描述了无法加载的资源(例如).

    您应该将原因作为构造函数参数传入,而不是调用initCause

    在实际代码中,您不会看到包含相同类型异常的异常抛出。关键是将实现级异常封装在更高级别的代码中,这样捕获异常的代码就不会有太多实现特定的特殊情况需要处理(并且实现细节不会渗透到代码中不需要关心的部分),而链接确保保留原始堆栈跟踪

    所以你会做一些类似的事情:

    private static void method1() throws HigherLevelException {
        try{
            System.out.println("Inside Try Block"+10/0);
        } catch(ArithmeticException e){
            throw new HigherLevelException(e);
        }
    }
    

    由于很多人认为检查异常是一个失败的实验(甚至不是点网选择复制它们),在很多情况下,更高级别的异常往往是未检查的异常。您将在Spring和Hibernate中看到这种模式

    在您的第一个示例中,捕获异常只是为了重新显示它应该不是必需的。stacktrace应该足以确定在何处生成异常,而无需记录和重新刷新。确保您有一个集中的位置来捕获和记录异常。

    initCause(e)
    返回
    。所以您只是在包装捕获的异常。