20-CS-694 Advanced Programming Techniques Spring 2012
Exceptions

Interfaces, Exceptions, Graphics, Animation, Threads, Reflection, Networking, RMI, JDBC, JNI

Previous     Next     All lectures

Introduction

Instructions for all applets:

All applets contain a 'Press Me' button. Click it.

    1.   ArrayProblem.java

    What happens when a program attempts to access an array element that does not exist? An exception is raised. If it is not caught a program may terminate in an ungraceful and untilmely fashion. In the following:
   for (int i=0 ; ; i++) {
      a[i] = i;
      out.append(i+"\n");
   }
numbers are printed until a[40] is accessed. Then the stack trace is printed.
 
    2.   HandleException.java

    The ArrayIndexOutOfBoundsException is caught in a try-catch block.
   try {
      for (int i=0 ; ; i++) { ... }
   } catch (ArrayIndexOutOfBoundsException e) {
      ...
   }
 
    3.   RunException.java

    Exceptions are a subclass of Throwable. There are many kinds of exceptions and they are organized in a tree-hierarchy as shown in this table. For example, the ArrayIndexOutOfBoundsException is a subclass of the RuntimeException. Hence catching a RuntimeException in the above will have the same effect as catching an ArrayIndexOutOfBoundsException as this applet shows.
 
    4.   TwoExceptions1.java

    More than one catch can be associated with a try. In this applet there is an attempt at accessing a null pointer before accessing the array so the NullPointerException is raised. Code for this looks as follows:
   try {
      ...
   } 
   catch (ArrayIndexOutOfBoundsException e) {
      ...
   } 
   catch (NullPointerException e) {
      ...
   }
 
    5.   TwoExceptions1.java

    As of Java 1.7 the following can be done to catch multiple exceptions:
   try {
      ...
   } 
   catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
      ...
   } 
 
    6.   YAE.java

    Same as above except a reference is made to a cell object and no exception is raised.
 
    7.   HandleException.java

    When an exception is raised, it "moves" up the system stack until it finds itself in a try-catch block where it is caught. This will be useful for long-distance escaping. An exception is thrown here, in doit:
   class First {
      void doit () { ... }
   }
That method gets called from this class:
   class Second {
      void doit () {  f.doit();  }
   }
and that method gets called and exception gets caught here:
   class HandleExceptionFrame ... {
      ...
      public void doit() {
         Second s = new Second(out);
         try {  s.doit();  }
         catch (ArrayIndexOutOfBoundsException e) {
            ...
         }
      }
   }
 
    8.   HandleException.java

    User code can throw exceptions arbitrarily, even if nothing illegal is going on. For example,
   void doit () {
      for (int i=0 ; ; i++) {
         if (i == 5) throw (new ArrayIndexOutOfBoundsException());
         a[i] = i;
         out.append(i+"\n");
      }
   }
 
    9.   HandleException.java

    A user may introduce new exception classes. This allows exceptions to be used for a variety of control purposes. In this applet a custom exception saves state when the exception is thrown and displays the state when it is caught. The following outlines how the exception class is created.
   class MyException extends Exception {
      JTextArea out; int i;
    
      MyException (JTextArea out, int i) { ... }

      void journeyEnd () { ... }
   }
The following shows that throwing this exception needs to be specified.
   void doit () throws MyException {  f.doit();  }
The following shows catching this exception.
   public void doit() {
      try {
         ...
      } catch (ArrayIndexOutOfBoundsException e) {
         ...
      } catch (MyException e) {
         e.journeyEnd();
         out.append("By the way, we really are at the top\n");
         text.setText(e.toString());
      }
   }  
 
    10.   Escape.java

    A simple example showing a very long and fast journey back in time to an early point in the system stack. A multiplication of a list of numbers is attempted. The numbers are stacked. If a 0 is encountered and exception is raised bypassing all of the multiplications.

Write numbers, separated by blanks, into the left text box and hit return. The left text box shows the product of the numbers and the right text box shows the number of multiplications executed.

The exception is defined like this:

   class MultiplyEscapeException extends Exception {
      MultiplyEscapeException () { }
      int escape () { return 0; }
   }
it is used like this:
   long multiply () throws MultiplyEscapeException { 
      ...
      long n = Integer.parseInt(t.nextToken());
      if (n == 0) throw new MultiplyEscapeException();
      ...
   }
it is caught like this:
   try {
      out.setText(String.valueOf(m.multiply()));
   }
   catch (MultiplyEscapeException e) {
      out.setText("0");
   }
 
    11.   RunException.java

    An exception can be caught then another thrown with a message and a cause. The cause is also Throwable (that is, an Error or an Exception). In this example an ArrayIndexOutOfBoundsException is caught by a catch as a RuntimeException object e. The result is a new RuntimeException is thrown with the message "Runtime caught at 41" and the cause e. That exception is caught one level higher (in method doit of class RunExceptionFrame) as object h. The stack trace of both h and e are displayed in the JTextArea, the latter due to h.getCause().getStackTrace(). Neither mentions an ArrayIndexOutOfBounds error and both originate at different lines in the code. However, h.getCause().toString() displays this error in the JTextField at the top of the applet.
 
    12.       In a try-catch with multiple catches, an Exception class cannot be caught before one of its subclasses - the code will not even compile. For example:
 try {
    ...
 } catch (RuntimeException e) {
    ...
 } catch (ArrayIndexOutOfBoundsException e) {
    ...
 } catch (NullPointerException e) {
    ...
 }
is illegal.
 
    13.   FinallyTest.java

    Regardless of whether the catch block is entered, the finally block is always executed. This example shows why this might be a good idea. A file is attempted to be opened. If the file cannot open an IOException is raised. If the file does not exist and IOException is caught. If the filename is A then p is the exception, otherwise it is null. If the while loop is executed a RuntimeException is raised. The finally block is then entered. If the file was not opened input is null. To control the demo, if the filename is A, B, or C, the if block is entered. The input stream is purposely set to null to cause the second catch to be entered.
 
    14.   FinallyTest.java

    The above may be templated and reused many times. The result is much cleaner code.