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();
}
}
}
The above outputs:
[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 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.
However, you can define your custom exception class and override equals()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With