20-CS-694 Advanced Programming Techniques Spring 2012
Exceptions

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

       Previous     Next     Applet Source     All lectures

Roll Your Own Exception

User creates an exception class and uses it to carry information to a calling procedure that catches objects of that class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;

class MyException extends Exception {
   JTextArea out;
   int i;
   
   MyException (JTextArea out, int i) {
      this.out = out;
      this.i = i;
      out.append("Starting the journey upward with value of i="+i+"\n");   
   }

   void journeyEnd () {
      out.append("Finally got to the top with value of i="+i+"\n");
   }
}

class First {
   JTextArea out;
   int a[] = new int[40];
   
   First (JTextArea out) {  this.out = out;  }
   
   void doit ( ) throws MyException {
      for (int i=0 ; ; i++) {
         if (i == 5) throw (new MyException(out, i));
         a[i] = i;
         out.append(i+"\n");
      }
   }
}

class Second {
   JTextArea out;
   First f;
   
   Second (JTextArea out) { 
      f = new First(out);  
      this.out = out; 
   }
   
   void doit () throws MyException {  f.doit();  }
}

class HandleExceptionFrame extends JFrame implements ActionListener {
   JTextArea out;
   JTextField text;
   JButton button;
   
   public HandleExceptionFrame () {
      setLayout(new BorderLayout());
      JPanel p = new JPanel();
      p.setLayout(new FlowLayout());
      p.add(text = new JTextField(30));
      p.add(new JLabel("  "));
      p.add(button = new JButton("Press Me"));
      add("North", p);
      add("Center", new JScrollPane(out = new JTextArea()));
      button.addActionListener(this);
      text.setEditable(false);
   }

   public void doit() {
      Second s = new Second(out);
      try {  s.doit();  }
      catch (ArrayIndexOutOfBoundsException e) {
         out.append("Caught array index out of bound exception");
      }
      catch (MyException e) {
         e.journeyEnd();
         out.append("By the way, we really are at the top\n");
         text.setText(e.toString());
      }
   }

   public void actionPerformed (ActionEvent evt) {  doit();  }
}

public class HandleException extends Applet {
   public void init () {
      HandleExceptionFrame hf = new HandleExceptionFrame();
      hf.setSize(500,300);
      hf.setVisible(true);
   }
}