Java Exception catch multiple exceptions with one catch statement

Introduction

Java Exception multi-catch can catch two or more exceptions within the same catch clause.

Here is a catch statement that uses the multi-catch feature to catch both ArithmeticException and ArrayIndexOutOfBoundsException:

catch(ArithmeticException | ArrayIndexOutOfBoundsException e) { 

The following program shows the multi-catch feature in action:

// Demonstrate the multi-catch feature.  
public class Main {
  public static void main(String args[]) {
    int a = 0, b = 0;
    int vals[] = { 1, 2, 3 };

    try {/*from w w  w.j a v a2  s .  com*/
      int result = a / b; // generate an ArithmeticException

      vals[10] = 1; // generate an ArrayIndexOutOfBoundsException
      // This catch clause catches both exceptions.
    } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
      System.out.println("Exception caught: " + e);
    }

    System.out.println("After multi-catch.");
  }
}
import java.io.FileInputStream;
import java.io.IOException;

public class Main {
   public static void main(String[] args) {
      start();// ww w . j  a  v a2  s . c  o m
      startClassic();
   }

   private static void startClassic() {
      try {
         Class<?> stringClass = Class.forName("java.lang.String");
         FileInputStream in = new FileInputStream("myFile.log"); // Can throw IOException
         in.read();

      } catch (IOException e) {
         System.out.println("There was an IOException " + e);
      } catch (ClassNotFoundException e) {

         System.out.println("There was a CLassCastException " + e);

      }
   }

   private static void start() {

      try {
         Class<?> stringClass = Class.forName("java.lang.String");
         FileInputStream in = new FileInputStream("myFile.log"); // Can throw IOException
         in.read();

      } catch (IOException | ClassNotFoundException e) {
         System.out.println("An exception of type " + e.getClass() + " was thrown! " + e);
      }
   }
}



PreviousNext

Related