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 using the throws keyword.
    public Item getItemFromList(int index) throws Exception{
       if(index >= array.length){
          throw new Exception("Out of Bounds " + index);
       }
       return array[index];
    }
    

When using the throws keyword and specifying a checked exception, the Java compiler will force the user of the getItemFromList() method to handle the exceptions thrown by the method. If the user does not handle the exception (either by catching it, or declaring it by including throws Exception in the calling method's header), the compiler produces a syntax error.

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);

}

In this case, if the function instead threw an ArrayIndexOutOfBoundsException, which is an unchecked exception, it would not be required by the compiler to either catch or declare it.