Exceptions

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.
    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
       }
    }
    

  2. Declare the exceptions that could occur from within a method.
    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 Java will enforce the user of the getItemFromList() method to catch the exceptions that could be generated by the function (i.e. Exception). When a user does not catch that exception, Java produce 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, Java requires use to place any statements that throw exceptions in a try/catch block.

    public void main(String[] args){
       try{
          Item i = getItemFromList(5);
       }
       catch(Exception e){
          // Do something with the exception
       }
    }