Why is catch exception not being printed after breaking NPE exception

try {
     String x = null;
     int y = x.length();
} catch (NullPointerException npe) {
     System.out.println("NPE Exception ");
} catch (Exception e) {
     System.out.println("Exception ");
}

      

Only "NPE Exception" is printed above the code snippet, not "Exception Exception Exception". Can anyone explain how NPE is of type RunTimeException and we know RunTimeException is a subtype of Exception?

+3


source to share


2 answers


Anyone Throwable

caught just once, the first catch block that can handle the exception



+7


source


You can only catch your exception once, or if you want to go to the next catch, throw your exception and catch it again. From Java7, you can catch this as alse:

catch( NullPointerException | SQLException ex ) { 
  System.out.println("NPE Exception ");

      



Multi-Catch blocks provide you with a cleaner way to handle exceptions, preventing duplicate code in multiple catch blocks. Note, however, that Exceptions that are peer-to-peer can only be placed in a block with multiple traps.

+3


source







All Articles