The Java Program: Ways.java

  1 // Ways.java -- five ways to leave your try block
  2 
  3 class NotCaughtException extends Exception {
  4    private final StringBuffer msg;
  5    NotCaughtException (StringBuffer b) { msg=b; msg.append("raise;");}
  6    StringBuffer getMsg () { return msg; }
  7 }
  8 
  9 class ToBeCaughtException extends NotCaughtException {
 10    ToBeCaughtException (StringBuffer b) { super(b); }
 11 }
 12 
 13 class Ways {
 14 
 15    static StringBuffer loop (int i) throws NotCaughtException {
 16       final StringBuffer r = new StringBuffer ("begin;");
 17       l: {
 18          try {
 19             switch (i) {
 20             default: r.append("norml;"); break;
 21             case 1:  r.append("break;"); break l;
 22             case 2:  r.append("retrn;"); return r;
 23             case 3:  throw new NotCaughtException (r);
 24             case 4:  throw new ToBeCaughtException (r);
 25             }
 26          } catch (ToBeCaughtException e) {
 27             r.append ("caught;");
 28          } finally {
 29             r.append ("fin;");
 30          }
 31          r.append( "after;");
 32       }
 33       return r.append("end;");
 34    }
 35 
 36    public static void main (String args[]) {
 37       for (int i=0;i<5;i++) {
 38          try {
 39             System.out.println (" "+i+": "+loop(i));
 40          } catch (NotCaughtException e) {
 41             System.out.println ("*"+i+": "+e.getMsg());
 42          }
 43       }
 44    }
 45 }