jlaufer
jlaufer

Reputation: 177

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?

Upvotes: 0

Views: 279

Answers (2)

Ofer Skulsky
Ofer Skulsky

Reputation: 743

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).

Upvotes: 0

mhash17
mhash17

Reputation: 379

It is throwing a NullPointerException but catching a ClassCastException (so no catching). It compiles but throws an unhandled NullpointerException.

Upvotes: 1

Related Questions