20-CS-4003-001 Organization of Programming Languages Fall 2017
Exceptions

Lambda calculus, Type theory, Formal semantics, Program analysis

    Previous     Next     All lectures        Code     Exception Hierarchy    

Where the exceptions are caught

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;

class Exception_2Frame
   extends JFrame implements ActionListener {
   JTextArea out;
   JTextField text;
   JButton button;
   int a[] = null;

   public Exception_2Frame () {
      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 (ArrayIndexOutOfBoundsException e) {
         out.append("Caught the out of bounds exception");
         text.setText(e.toString());
      }
   }

   public void actionPerformed (ActionEvent evt) {
      try {
         doit();
      } catch (Exception e) {
         out.append("Exception caught in actionPerformed\n");
         text.setText(e.toString());
      }
   }
}

public class exception_2
   extends Applet implements ActionListener {
   JButton go;

   public void init () {
      setLayout(new BorderLayout());
      setBackground(new Color(255,255,223));
      add("Center", go = new JButton("Applet"));
      go.addActionListener(this);
   }

   public void actionPerformed (ActionEvent evt) {
      Exception_2Frame hf = new Exception_2Frame();
      hf.setSize(500,300);
      hf.setVisible(true);
   }
}
 -  Now a NullPointerException is raised in doit. Since this exception is above the ArrayIndexOutOfBoundsException in the exception hierarchy it is not caught in doit. But it is caught one level above that in actionPerformed.