Nicola Ambrosetti
Nicola Ambrosetti

Reputation: 2705

StringIndexOutOfBoundsException cannot take "cause" in constructor

Java Exceptions usually have a (among others) a constructor that can take a Throwable cause, so that when rethrowing an exception one can give the original exception and it will appear in the log as

com.stacktrace.from.application.exception...
Caused by
net.stacktrace.of.code.throwing.original.exception...

However StringIndexOutOfBoundsException has only (), (int index) or (String s). No constructor accepts a cause!!

Looking at the type hierarchy it seems that both Exception and RuntimeException are fine, but already IndexOutOfBoundsException has lost the (String s, Throwable cause) constructor.

I know that constructors are not inherited, but WHY would one not have a similar one for IndexOutOfBoundsException and StringIndexOutOfBoundsException?

Upvotes: 1

Views: 95

Answers (2)

plastique
plastique

Reputation: 1204

The IndexOutOfBoundsExceptionis not the only Throwable without the cause parameter constructor. For exampleNullPointerException is also the case. I'm sure there is more. The explanation is simple these are the root causes. They are not caused by another exceptions, but thrown directly by JVM. Either programmer's mistake or external source is causing them.

You may of course use constructor with description of the exception when creating and throwing it yourself.

Upvotes: 2

Grisha Weintraub
Grisha Weintraub

Reputation: 7986

It seems that exceptions that are not supposed to have a cause do not have a constructor with a Throwable argument. You still can add a cause to any exception through initCause method though :

    try{
        "aaa".substring(10);
    }catch(IndexOutOfBoundsException e){
        e.initCause(new RuntimeException("some cause exception"));
        throw e;
    }

Upvotes: 1

Related Questions