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

This stops printing at 39. The reason is an ArrayIndexOutOfBoundsException is raised at 40.

// ArrayIndexOutOfBoundsException is raised when
// a[40] = 40 is attempted
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;

class ArrayProblemFrame extends JFrame implements ActionListener {
   JTextArea out;
   JTextField text;
   JButton button;
   int a[] = new int[40];
   
   public ArrayProblemFrame () {
      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() {
      for (int i=0 ; ; i++) {
         a[i] = i;
         out.append(i+"\n");
      }
   }

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

public class ArrayProblem extends Applet {
   public void init () {
      ArrayProblemFrame af = new ArrayProblemFrame();
      af.setSize(500,300);
      af.setVisible(true);
   }
}