The Java Program: Value.java

  1 // Value.java:  exception instances are values in Java
  2 
  3 // Exceptions are subclasses of the class "Exception", so
  4 // user-defined exceptions are created just like classes.
  5 // Consequently, subclassing and constructors with arguments
  6 // can be used to advantage in exception handling.
  7 
  8 import java.io.IOException;
  9 
 10 class An_Exception extends Exception {}
 11 
 12 class A_Sub_Exception extends An_Exception {}
 13 
 14 class One_Exception extends Exception {
 15    int argument;
 16    public One_Exception (int i) { argument=i; }
 17 }
 18 
 19 class MyIOException extends IOException {
 20    public MyIOException (String s) {super (s);};
 21 }
 22 
 23 public class Value {
 24 
 25    public static void main (String argv[]) {
 26       try {
 27          final int i = Integer.parseInt (argv[0]);
 28          switch (i) {
 29          case 0: throw new An_Exception();
 30          case 1: throw new A_Sub_Exception();
 31          case 2: throw new One_Exception (5);
 32          case 3: throw new MyIOException ("not really!");
 33          }
 34       } catch (One_Exception e) {
 35          System.out.println (e.argument);
 36       } catch (An_Exception e) {
 37          e.printStackTrace (System.err);
 38       } catch (MyIOException e) {
 39          e.printStackTrace (System.err);
 40       } catch (IOException e) {
 41          e.printStackTrace (System.err);
 42       } catch (Exception e) {
 43          e.printStackTrace (System.err);
 44       }
 45    }
 46 }