20-CS-694 Advanced Programming Techniques Spring 2012
Exceptions for control

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

       Previous     Next     Applet Source     All lectures

Add Up Exception for control

In order to stop at the first solution we define an Out exception to be used in checkit() of Evaluate in case assert_() succeeds. An Out exception is only caught at the top level in solve of Evaluate. Therefore, throwing an Out terminates computation (after a solution is printed before throwing it). If the top level is reached via a thrown Up, there is no solution and a message is printed.

To streamline the coding process for future users the Puzzle class is created to hold v(), which is required by the Variable interface, and assert_(), which should never change from use to use.

   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import java.applet.*;
   interface Variable { void checkit() throws Up, Out;  int v();  }
   class Up extends Exception { }
   class Out extends Exception { }
   class Puzzle {
      public int v() { return 0; }
      public void assert_ (boolean e) throws Up { if (!e) throw new Up(); }
   class Choose implements Variable {
      Variable next_for;
      int val = 0;
      Choose (Variable next_for) { this.next_for = next_for; }
      public void checkit () throws Up, Out {
         for ( ; val < 2 ; val++) try { next_for.checkit(); } catch (Up up) { } 
         val = 0;
         throw new Up();
      public int v() { return val; }
   class Evaluate extends Puzzle implements Variable {
      Variable i,j,k;
      E problem;
      public Evaluate (E problem) {  
         this.problem = problem; 
         problem.out.append("\nSolve: ((1-i)*j + i*(1-k) + (1-j)*k)\n\n");
      public void checkit() throws Up, Out {
         assert_((((1-i.v())*j.v()+i.v()*(1-k.v())+(1-j.v())*k.v()) % 2) == 1);
         problem.out.append("i="+i.v()+" j="+j.v()+" k="+k.v()+"\n");
         throw new Out();
      public void solve () {
         try {
            k = new Choose(this);
            j = new Choose(k);
            i = new Choose(j);
         } catch (Up up) {
            problem.out.append("No solution\n");
         } catch (Out out) {  }
   public class E extends Applet implements ActionListener {
      JTextArea out;
      JButton button;
      public void init () {
         setLayout(new FlowLayout());
         add(new JScrollPane(out = new JTextArea(16,30)));
         add(button = new JButton("Press Me"));
      public void doit() {
         Evaluate eval = new Evaluate(this);
      public void actionPerformed (ActionEvent evt) {  doit(); }