Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't I compare Exception objects for equality?

Tags:

java

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)
like image 749
Marcus Junius Brutus Avatar asked Jan 11 '23 06:01

Marcus Junius Brutus


1 Answers

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().

like image 193
Juvanis Avatar answered Jan 22 '23 00:01

Juvanis