user3745870
user3745870

Reputation: 321

How to catch exception in Java?

I am getting following exception in my code and I want to catch the inner exception. Is it possible to catch that?

java.lang.RuntimeException: error
some stack trace
some stack trace
some stack trace
! Caused by: java.util.concurrent.TimeoutException: null
some stack trace
some stack trace
some stack trace

Lets say I have following code.

function abc() {
  try{
    xyz()
  } catch (TimeoutException e) {
     do stuff
  }
}

xyz() function is generating that exception. Would catching the TimeoutException like this work?

Upvotes: 0

Views: 602

Answers (3)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

No, you can't catch a RuntimeException with catch(TimeoutException e).

However, you could do

} catch (RuntimeException e) {
  Throwable cause = e.getCause(); 
}

to get the cause.

Upvotes: 1

Thomas Fritsch
Thomas Fritsch

Reputation: 10127

You cannot directly catch a RuntimeException caused by a TimeoutException.

But you achieve it like this:

    try {
        xyz();
    } catch (RuntimeException e) {
        if (e.getCause() instanceof TimeoutException) {
            // handle TimeoutException
            doStuff();
        } else {
            // rethrow all exceptions with other causes
            throw e;
        }
    }

Upvotes: 1

yshavit
yshavit

Reputation: 43391

You can't do it directly. You have to catch the outer exception, check its getCause() to see if it's what you want, and then either handle that cause or re-throw the top-level exception.

(You could also technically re-throw just the inner one, but I would strongly discourage that; the stack trace will be very confusing, and it'll be harder to debug -- especially a year from now, when you've forgotten that you did that.)

Upvotes: 3

Related Questions