Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

Java 7 new feature : Catching multiple exception types in a single catch block.

Program to demonstrate Java 7 new feature : Catching multiple exception types in a single catch block

package com.hubberspot.java7;

import java.util.InputMismatchException;

public class MultipleExceptionsCatching {

 public static void main(String[] args) {

  try {

   // Scenario 1 :  we will pass int parameter
   // as -1, which will throw InputMismatchException 
   int i = Integer.parseInt("String 1");

   // Scenario 2 : we will pass String as a int to
   // parse. It will throw NumberFormatException 

   // int i = Integer.parseInt("String 1");

   if(i <= 0) { 

    throw new InputMismatchException();

   }
   // Initially prior to Java 7, we would have coded multiple exceptions
   // into various catch blocks as : 
   // 
   // try { 
   //    throw new NumberFormatException() or throw new InputMismatchException()
   // }
   // catch(NumberFormatException nfe) { 
   //    nfe.printStackTrace();
   // }
   // catch(InputMismatchException ime) { 
   //    ime.printStackTrace();
   // }

   // But with introduction of Java 7 we can handle multiple 
   // exceptions in a single catch block itself
   // see the code below : 

  } catch(NumberFormatException | InputMismatchException e) { 

   e.printStackTrace();
  }
 }

}


Output of the program : 

Scenario 1 : 















Scenario 2 : 


 
 
© 2021 Learn Java by Examples Template by Hubberspot