Search code examples
javaexceptionruntimeexceptionthrowablerandoop

Throwable and Exception in Java


Suppose I have a class named BugException which extends from RuntimeException And BugException has a copy constructor which takes a Throwable.

This code compiles and typechecks:

Throwable e = ...;
if (e instanceof BugException) {
   throw new BugException(e);
}

Why is it that:

Throwable e = ...;
if (e instanceof BugException) {
   throw e;
}

Does not compile and gives the error message: unhandled exception. java.lang.Throwable. ?

Why is this unnecessary wrapping necessary to satisfy the typechecker?


Solution

  • At compile time, it is not know what kind of exception e is. It might be a checked Exception, in which case the compiler will need you to either wrap the throw in a try/catch or make the method throw it.

    However, if you explicitly cast the unchecked exception, then it will compile.

    Throwable e = ...;
    if (e instanceof BugException) {
       throw (BugException) e;
    }