为什么我不能比较Exception对象是否相等? [英] why can't I compare Exception objects for equality?

查看:64
本文介绍了为什么我不能比较Exception对象是否相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SSCCE:

import java.util.Objects;
public class FooMain {

    private static Exception foo() {
        try {
            throw new Exception();
        } catch (Exception e) {
            return e;
        }
    }


    public static void main(String args[]) {
        final int N = 2;
        Exception es[] = new Exception[N];
        for (int i = 0 ; i < N ; i++)
            es[i] = foo();
        System.out.printf("Exceptions are equal? %b\n", Objects.equals(es[0], es[1]));
        for (int i = 0 ; i < N ; i++) {
            System.out.printf("follows exception %d:\n", i);
            es[i].printStackTrace();
        }
    }
}

以上输出:

 [java] Exceptions are equal? false
 [java] follows exception 0:
 [java] follows exception 1:
 [java] java.lang.Exception
 [java]     at FooMain.foo(FooMain.java:6)
 [java]     at FooMain.main(FooMain.java:17)
 [java] java.lang.Exception
 [java]     at FooMain.foo(FooMain.java:6)
 [java]     at FooMain.main(FooMain.java:17)

推荐答案

Exception类从 Object 继承其 equals()方法,并且不会覆盖它.每次都创建新的Exception实例,它们是内存中的不同对象.即使它们的堆栈跟踪相同,它们在内存中的对象分配仍然不同,并且使用默认的equals()方法,它们并不相同.

Exception class inherits its equals() method from Object and doesn't override it. You create new Exception instances each time which are different objects in the memory. Even though their stack traces are the same, they still have different object allocation in the memory and with the default equals() method, they are not the same.

但是,您可以定义自定义异常类并覆盖 equals().

However, you can define your custom exception class and override equals().

这篇关于为什么我不能比较Exception对象是否相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆