Notes on Exceptions

 

Exceptions are used for handling exceptional conditions such as errors. The concept of exceptions is not well supported in most other languages.  Exceptions remove error handling from the mainline code.  It relieves the programmer from the need to check the return status of every method call.

Exception handling is slow compared to other processing.

 

     try {

          // stuff

     } catch (exceptionType identifier) {

          // what to do

     }

 

or

 

     try {

          // stuff

     } catch (exceptionType1 identifier) {

          // what to do

     } catch (exceptionType2 identifier) {

          // what to do for two

     } finally {

          // always do this

     }

 

 

Your methods can throw an exception if it discovers an error.

 

     throw new exceptiontype();

 

You can re-throw an exception from a catch block

 

     try {

          // something

     } catch (Exception e) {

          throw e;

     }

 

If a method is going to throw an exception, it must state that in the method declaration.

 

public void abc() throws IllegalArgumentException {

}

 

If you use a method that can throw and exception, you must specify in your program how that exception should be handled.  You must either execute the method in a try/catch block or specify that the method will throw the exception.

 

The Throwable class, parent of all Exceptions, has some useful methods.

getMessage() will return a String containing an error message if one exists.

printStackTrace() will print a trace of were this method was called.

 

     try {
         int a[] = new int[2];
         a[4];
     } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("exception: " + e.getMessage());
         e.printStackTrace();
     }

 

Exceptions will be caught by the first catch in the call stack.

 

Exception

The parent class of all other exceptions.

ArithmeticException

Thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero" throws an instance of this class.

EmptyStackException

Thrown by methods in the Stack class to indicate that the stack is empty.

IllegalArgumentException

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

IndexOutOfBoundsException

Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.

NegativeArraySizeException

Thrown if an application tries to create an array with negative size.

NoSuchElementException

Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.

NullPointerException

Thrown when an application attempts to use null in a case where an object is required.

IOException

Signals that an I/O exception of some sort has occurred.