'Expecting compile time error in try/catch statement
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
?
Solution 1:[1]
It is throwing a NullPointerException but catching a ClassCastException (so no catching). It compiles but throws an unhandled NullpointerException.
Solution 2:[2]
In Java there are 3 types of throwable:
- Error - probably nothing to recover.
- Exception - needs to be declared and handled (checked)
- Runtime Exception - does not need to be declared (unchecked)
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).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | user3192295 |
Solution 2 | Community |