why can't I compare Exception objects for equality?
java
Solution
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()`.
Problem
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) ```