简体   繁体   中英

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM