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





     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];
     } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("exception: " + e.getMessage());


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



The parent class of all other exceptions.


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


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


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


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.


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


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


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


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