20-CS-694 Advanced Programming Techniques Spring 2012
Exceptions

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

       Previous     Next     Exception Hierarchy      Applet Source     All lectures

Catching the Runtime Exception

// RuntimeException is higher in the hierarchy
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;

class RunExceptionFrame extends JFrame implements ActionListener {
   JTextArea out;
   JTextField text;
   JButton button;
   int a[] = new int[40];
      
   public RunExceptionFrame () {
      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() {
      try {
         for (int i=0 ; ; i++) {
            a[i] = i;
            out.append(i+"\n");
         }
      }
      catch (RuntimeException e) {
         out.append("Caught the runtime exception");
         text.setText(e.toString());
      }
   }

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

public class RunException extends Applet {
   public void init () {
      RunExceptionFrame rf = new RunExceptionFrame();
      rf.setSize(500,300);
      rf.setVisible(true);
   }
}