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

Throw Your Own Exception

Throw your own ArrayIndexOutOfBoundsException even if no illegal access to an array element occurred.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;

class First {
   JTextArea out;
   int a[] = new int[20];
   
   First (JTextArea out) {  this.out = out;  }
   
   void doit () {
      for (int i=0 ; ; i++) {
         if (i == 5) throw (new ArrayIndexOutOfBoundsException());
         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 () {  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 the out of bounds exception");
         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);
   }
}