20-CS-694 Advanced Programming Techniques Spring 2012
Exceptions

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

    Previous     Next     All lectures        Code    

Basic Use

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

class Exception_1Frame 
   extends JFrame implements ActionListener {
   JTextArea out;
   JTextField text;
   JButton button;
   int a[] = new int[40];
   
   public Exception_1Frame () {
      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) { 
         text.setText(e.toString()); 
      }
   }
}

public class exception_1 
   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_1Frame hf = new Exception_1Frame();
      hf.setSize(500,300);
      hf.setVisible(true);
   }
}
 -  A typical handling of an exception. In this case an ArrayIndexOutOfBoundsException. Control flow is diverted to a catch block for special processing. In this case the for loop is interrupted and a statement saying the exception is caught is printed. If an exception is raised and is not caught by the catch of doit, it will be caught by the catch of actionPerformed.