Exceptions in Java

Example

class NullArrayException extends Exception{
    public NullArrayException( String errorString ) {
        super(errorString);
    }
}
class NegativeIndexException extends Exception{
    public NegativeIndexException( String errorString ) {
        super(errorString);
    }
}
class IndexOutofBoundsException extends Exception{
    public IndexOutofBoundsException( String errorString ) {
        super(errorString);
    }
}
 
public class ExceptionExample {
 
    public static void swap( int [] A, int i, int j ) 
        throws NullArrayException, NegativeIndexException, IndexOutofBoundsException 
    {
        if( A == null )
            throw new NullArrayException("swap(): input array is null.");
            
        if( i < 0 || j < 0 )
            throw new NegativeIndexException("swap(): one of input indices is < 0.");
            
        if( i >= A.length || j >= A.length )
            throw new IndexOutofBoundsException(
                      "swap(): one of input indices is >= A.length.");
        
        int temp = A[i]; A[i] = A[j]; A[j] = temp;    
    }
    
    public static void main(String[] args) {
        try{
            int [] A = null;
            int [] B = {3, 5, 7};
            
            // Following statement triggers NullArrayException
            swap(A, 0, 1); //comment out to test next one.
            
            // Following statement triggers IndexOutofBoundsException
            swap(B, 1, 3); //comment out to test next one.
            
            // Following statement triggers NegativeIndexException 
            swap(B, -1, 2);
        }
        catch(NullArrayException e){
            System.out.println("Null array exception in \n" + e.toString());
        }
        catch(NegativeIndexException e){
            System.out.println("Negative index exception in \n" + e.toString());
        }
        catch(IndexOutofBoundsException e){
            System.out.println("Index  out of bounds in \n" + e.toString());
        }
    }
}

URL

http://cs-people.bu.edu/tvashwin/cs112_spring09/exceptions.html