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

Catching Two Kinds of Exceptions

// Handle two exceptions in same try-catch block
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;

class Cell {
   Object object;
   Cell next;
   
   Cell (Object object, Cell next) {
      this.object = object;
      this.next = next;
   }

   Object objectOf() { return object; }
}

class TwoExceptionsFrame extends JFrame implements ActionListener {
   JTextArea out;
   JTextField text;
   JButton button;
   int a[] = new int[40];
   Cell cell = null;
   
   public TwoExceptionsFrame () {
      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 {
         cell.objectOf();
         for (int i=0 ; ; i++) {
            a[i] = i;
            out.append(i+"\n");
         }
      }
      catch (ArrayIndexOutOfBoundsException e) {
         // Will catch a problem with cell.objectOf()
         out.append("Caught the Out of Bounds Exception\n");
         text.setText(e.toString());
      }
      catch (NullPointerException e) {
         // Will catch a problem with a[i] = i
         out.append("Caught the Null Pointer Exception\n");
         text.setText(e.toString());
      }
   }

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

public class TwoExceptions extends Applet {
   public void init () {
      TwoExceptionsFrame tf = new TwoExceptionsFrame();
      tf.setSize(500,300);
      tf.setVisible(true);
   }
}