Saturday, February 1, 2014

Try Catch Exception Matching

Source:
public class ExceptionMatching {
 
   public static void main(String[] args) {
      try {
         method();
      } catch (NullPointerException e) {
         System.out.println("Exception match: NullPointerException");
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception match: ArrayIndexOutOfBoundsException");
      } catch (Exception e) {
         System.out.println("Exception not matched " + e.toString());
      }
 
   }
 
   public static void method() {
      int x[] = new int[10];
 
      // this should throw an ArrayIndexOutOfBoundsException
      int y = x[21];
   }
}

Output:
   $ java ExceptionMatching 
   Exception match: ArrayIndexOutOfBoundsException