为什么我不能比较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()
.