Baitazar Hametov
Baitazar Hametov

Reputation: 13

How to correctly handle nested exception inside catch block

I have the following piece of code, and I'm trying to understand how can I correctly handle exception in catch block so both exceptions (mainException and anotherException) are thrown so in case of anotherException we do not lose info from mainException. Also code smells bad - is this kind of try-catch usage is some kind of anti-pattern? Is there a better/correct way to handle this kind of situations?

        try {
            -some code-
        } catch (RuntimeException mainException) {
            try {
                -another code-
            } catch (Exception anotherException) {
                throw anotherException;
            } finally {
                throw mainException;
            }
        }

Upvotes: 1

Views: 976

Answers (1)

Andreas
Andreas

Reputation: 159185

In Java 7, as part of the work on try-with-resources, the Throwable class was extended with support for suppressed exceptions, specifically intended for scenarios like this.

public static void main(String[] args) throws Exception {
    try {
        throw new RuntimeException("Foo");
    } catch (RuntimeException mainException) {
        try {
            throw new Exception("Bar");
        } catch (Exception anotherException) {
            mainException.addSuppressed(anotherException);
        }
        throw mainException;
    }
}

Output (stacktrace)

Exception in thread "main" java.lang.RuntimeException: Foo
    at Test.main(Test.java:5)
    Suppressed: java.lang.Exception: Bar
        at Test.main(Test.java:8)

Upvotes: 4

Related Questions