Catching multiple exceptions

If multiple blocks match the exception type, the first block that matches the type of the exception catches it.

public class HelloThere {

  public static void main(String[] args) {
  
    int repeat;
    
    try {
      // possible NumberFormatException and ArrayIndexOutOfBoundsException
      repeat = Integer.parseInt(args[0]); 
      
      // possible ArithmeticException
      int n = 2/repeat;
      
      // possible StringIndexOutOfBoundsException
      String s = args[0].substring(5);
    }
    catch (NumberFormatException e) {
      // print an error message
      System.err.println("Usage: java HelloThere repeat_count" );
      System.err.println(
       "where repeat_count is the number of times to say Hello" );
      System.err.println("and given as an integer like 1 or 7" );
      return;
    }
    catch (ArrayIndexOutOfBoundsException e) {
      // pick a default value
      repeat = 1;
    }
    catch (IndexOutOfBoundsException e) {
      // ignore it
    }
    catch (Exception e) {
      // print an error message and exit
      System.err.println("Unexpected exception");
      e.printStackTrace();
      return;
    }
    
    for (int i = 0; i < repeat; i++) {
      System.out.println("Hello");
    }
  
  }

}

It's rare to catch a generic Error or Throwable because it's really hard to clean up after them in the general case.


Previous | Next | Top | Cafe au Lait

Copyright 1999 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified June 17, 1999