Home > Enterprise >  Expecting compile time error in try/catch statement
Expecting compile time error in try/catch statement

Time:05-13

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?

CodePudding user response:

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

CodePudding user response:

in Java there are 3 types of throwable:

  • error - probably nothing to recover.
  • exception - needs to be declared and handled (checked)
  • run time 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.
you also 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).

  •  Tags:  
  • java
  • Related