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    

A user can create an Exception type

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

class MyException extends Exception {
   JTextArea out;
   int i;
   
   MyException (JTextArea out, int i) {
      this.out = out;
      this.i = i;
      out.append("Starting the journey upward"+
                 "with value of i="+i+"\n");
   }

   void journeyEnd () {
      out.append("Finally got to the top with"+
                 "value of i="+i+"\n");
   }
}

class First {
   JTextArea out;
   int a[] = new int[40];
   
   First (JTextArea out) {  this.out = out;  }
   
   void doit ( ) throws MyException {
      for (int i=0 ; ; i++) {
         if (i == 5) throw (new MyException(out, i));
         a[i] = i;
         out.append(i+"\n");
      }
   }
}

class Second {
   JTextArea out;
   First f;
   
   Second (JTextArea out) { 
      f = new First(out);  
      this.out = out; 
   }
   
   void doit () throws MyException {  f.doit();  }
}

class Exception_3Frame 
   extends JFrame implements ActionListener {
   JTextArea out;
   JTextField text;
   JButton button;
   
   public Exception_3Frame () {
      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() {
      Second s = new Second(out);
      try {  
         s.doit();  
      } catch (ArrayIndexOutOfBoundsException e) {
         out.append("Caught ArrayException");
      } catch (MyException e) {
         e.journeyEnd();
         out.append("By the way, we really are"+
                    "at the top\n");
         text.setText(e.toString());
      }
   }

   public void actionPerformed (ActionEvent evt) {
      try {	
         doit();
      } catch (Exception e) {
         out.append("Exception: "+e.toString());
      }
   }
}

public class exception_3 
   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_3Frame hf = new Exception_3Frame();
      hf.setSize(500,300);
      hf.setVisible(true);
   }
}
 -  A user can create an Exception class and use it in creative ways. This example illustrates the use of a created Exception object.