[ACCEPTED]-Is there inner exception concept in java-exception

Accepted answer
Score: 31

Absolutely - you can retrieve the inner 5 exception (the "cause") using 4 Throwable.getCause(). To create an exception with a cause, simply 3 pass it into the constructor. (Most exceptions 2 have a constructor accepting a cause, where 1 it makes sense.)

Score: 12

You can set the inner exception (AKA the 8 cause) in two ways. If you're instantiating 7 the exception yourself, pass the inner exception 6 to the (outer) exception's constructor, e.g.

try {
    // some code that throws innerException
} catch (Exception innerException) {
    throw new OuterException(innerException);
}

On 5 the other hand, if the outer exception does 4 not have a constructor that allows you to 3 set the inner exception, or you don't instantiate 2 the outer exception yourself, you can set 1 it using

outerException.initCause(innerException);
Score: 6

Since Java 1.4, java.lang.Throwable has constructors that take 4 another Throwable as parameter, and a getCause() method that 3 returns it. Pretty much all exceptions in 2 the standard API and most of those implemented 1 in other libraries make use of this facility.

Score: 1

All the exceptions can be chained in Java. This 4 means that you may throw an exception and 3 provide another exception (Throwable in 2 fact) as the cause of the exception you're 1 throwing. Look at the javadoc for Exception.

More Related questions