javacodex.com
Java Examples
Java Examples
memu home questions

Exception Matching

You associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block.
   try {
      .....
   } catch (ExceptionType name) {
      .....
   } catch (ExceptionType name) {
      ....
   }
Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name.

http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html

Source: (ExceptionMatching.java)

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

Contact: javacodex@yahoo.com