Reputation: 177
Why does this code compile an run fine?
public static void main(String[] args) {
try {
throw new NullPointerException();
} catch (ClassCastException e) {
}
}
More specifically, how does ClassCastException
handle a NullPointerException
? Also how is it possible for throw new NullPointerException
to throw a ClassCastException
?
Upvotes: 0
Views: 279
Reputation: 743
In Java there are 3 types of throwable:
The compiler (by default) lets you use catch for any exception and run time exception.
In your code, you are throwing an unchecked exception (NullPointerException
) so there is no need for the try/catch.
Moreover, you have a try/catch for some random run time exception (ClassCastException
).
You can use any static code analysis tool to fined this logical bug (or change your ide's defaults).
Upvotes: 0
Reputation: 379
It is throwing a NullPointerException but catching a ClassCastException (so no catching). It compiles but throws an unhandled NullpointerException.
Upvotes: 1