1

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?

waylonion
  • 6,866
  • 8
  • 51
  • 92

1 Answers1

5

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;
}
Michael Markidis
  • 4,163
  • 1
  • 14
  • 21