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

Array Exception

The Array Index Out Of Bounds Exception is Caught

// Add try-catch to handle exception
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;

class HandleExceptionFrame extends JFrame implements ActionListener {
   JTextArea out;
   JTextField text;
   JButton button;
   int a[] = new int[40];
   
   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);
   }

   public void doit() {
      try {
         for (int i=0 ; ; i++) {
            a[i] = i;
            out.append(i+"\n");
         }
      }
      catch (ArrayIndexOutOfBoundsException e) {
         out.append("Caught the out of bounds exception");
         text.setText(e.toString());
      }
   }

   public void actionPerformed (ActionEvent evt) {  
      try { doit(); } catch (Exception e) { text.setText(e.toString()); }
   }
}

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