简体   繁体   中英

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 ?

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

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

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