Handling Checked Exceptions

Checked exceptions are subject to the "Catch or Declare Rule". This means you must do one of the following:

  1. Catch the exception in the method that would generate the exception using a try/catch block. Notice the throwing of the Exception object using the keyword throw.
    public Item getItemFromList(int index){
       try{
          if(index >= array.length)
             throw new Exception("Out of Bounds" + index);
          else{
             return array[index];
          }
       }
       catch(Exception e){
          // handle the exception generated in the try block
          e.printStackTrace();
       }
    }
    

  2. Declare the exception that could occur from within a method. Notice the throwing of the Exception object using the keyword throw.
    public Item getItemFromList(int index) throws Exception{
       if(index >= array.length){
          throw new Exception("Out of Bounds" + index);
       }
       return array[index];
    }
    

When using the Declare method, the Java compiler will force the user of the getItemFromList() method to handle the exceptions thrown by the method (i.e. the "Out of Bounds" Exception). If the user does not handle the exception (i.e. catch or declare the exception), the compiler produces a syntax error until the user properly handles that exception.

public void main(String[] args){
   Item i = getItemFromList(5); // this violates the Catch or Declare Rule
                                // causing a syntax error
}

To fix the syntax error that is produced in the previous example, the Java compliler requires placing any statement that throws a checked exception in a try/catch block,

public void main(String[] args){
   try{
      Item i = getItemFromList(5);
   }
   catch(Exception e){
      // Do something with the exception
      System.err.println(e.getMessage());
   }
}
or that the exception be declared as being thrown.
public void main(String[] args)throws Exception{

   Item i = getItemFromList(5);

}