Demonstrates exception chaining : Exceptions « Language Basics « Java






Demonstrates exception chaining

Demonstrates exception chaining
          

// : c09:DynamicFields.java
// A Class that dynamically adds fields to itself.
// Demonstrates exception chaining.
// {ThrowsException}
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.

class DynamicFieldsException extends Exception {
}

public class DynamicFields {

  private Object[][] fields;

  public DynamicFields(int initialSize) {
    fields = new Object[initialSize][2];
    for (int i = 0; i < initialSize; i++)
      fields[i] = new Object[] { null, null };
  }

  public String toString() {
    StringBuffer result = new StringBuffer();
    for (int i = 0; i < fields.length; i++) {
      result.append(fields[i][0]);
      result.append(": ");
      result.append(fields[i][1]);
      result.append("\n");
    }
    return result.toString();
  }

  private int hasField(String id) {
    for (int i = 0; i < fields.length; i++)
      if (id.equals(fields[i][0]))
        return i;
    return -1;
  }

  private int getFieldNumber(String id) throws NoSuchFieldException {
    int fieldNum = hasField(id);
    if (fieldNum == -1)
      throw new NoSuchFieldException();
    return fieldNum;
  }

  private int makeField(String id) {
    for (int i = 0; i < fields.length; i++)
      if (fields[i][0] == null) {
        fields[i][0] = id;
        return i;
      }
    // No empty fields. Add one:
    Object[][] tmp = new Object[fields.length + 1][2];
    for (int i = 0; i < fields.length; i++)
      tmp[i] = fields[i];
    for (int i = fields.length; i < tmp.length; i++)
      tmp[i] = new Object[] { null, null };
    fields = tmp;
    // Reursive call with expanded fields:
    return makeField(id);
  }

  public Object getField(String id) throws NoSuchFieldException {
    return fields[getFieldNumber(id)][1];
  }

  public Object setField(String id, Object value)
      throws DynamicFieldsException {
    if (value == null) {
      // Most exceptions don't have a "cause" constructor.
      // In these cases you must use initCause(),
      // available in all Throwable subclasses.
      DynamicFieldsException dfe = new DynamicFieldsException();
      dfe.initCause(new NullPointerException());
      throw dfe;
    }
    int fieldNumber = hasField(id);
    if (fieldNumber == -1)
      fieldNumber = makeField(id);
    Object result = null;
    try {
      result = getField(id); // Get old value
    } catch (NoSuchFieldException e) {
      // Use constructor that takes "cause":
      throw new RuntimeException(e);
    }
    fields[fieldNumber][1] = value;
    return result;
  }

  public static void main(String[] args) {
    DynamicFields df = new DynamicFields(3);
    System.out.println(df);
    try {
      df.setField("d", "A value for d");
      df.setField("number", new Integer(47));
      df.setField("number2", new Integer(48));
      System.out.println(df);
      df.setField("d", "A new value for d");
      df.setField("number3", new Integer(11));
      System.out.println(df);
      System.out.println(df.getField("d"));
      Object field = df.getField("a3"); // Exception
    } catch (NoSuchFieldException e) {
      throw new RuntimeException(e);
    } catch (DynamicFieldsException e) {
      throw new RuntimeException(e);
    }
  }
} ///:~


           
         
    
    
    
    
    
    
    
    
    
  








Related examples in the same category

1.Illustrate various Exceptions Illustrate various Exceptions
2.Experience exceptionsExperience exceptions
3.StackTrace
4.Getting the Stack Trace of an Exception
5.What happens if a method declares an unchecked exception?
6.Simple demo of exceptionsSimple demo of exceptions
7.Simple demo of exceptions, with finally clauseSimple demo of exceptions, with finally clause
8.ThreadBasedCatcher - Demonstrate catching uncaught exceptions
9.Exception CatcherException Catcher
10.Turning off Checked exceptions
11.Finally is always executedFinally is always executed
12.Demonstrating the Exception MethodsDemonstrating the Exception Methods
13.Further embellishment of exception classesFurther embellishment of exception classes
14.The finally clause is always executedThe finally clause is always executed
15.Your own Exception classYour own Exception class
16.Catching exception hierarchiesCatching exception hierarchies
17.How an exception can be lost
18.Exception in main method
19.Ignoring RuntimeExceptionsIgnoring RuntimeExceptions
20.Demonstrating fillInStackTrace()Demonstrating fillInStackTrace()
21.Put printStackTrace() into a String: redirect the StackTrace to a String with a StringWriter/PrintWriter
22.Rethrow a different object from the one that was caughtRethrow a different object from the one that was caught
23.Inheriting your own exceptionsInheriting your own exceptions
24.Overridden methods may throw only the exceptions
25.Returns the output of printStackTrace as a String.
26.Locates a particular type of exception
27.Throw Exception OutThrow Exception Out
28.Get Deepest ThrowableGet Deepest Throwable
29.Make a string representation of the exception
30.Utility methods for dealing with stack traces
31.Returns the root cause of an exception
32.Utility class to work with throwables
33.Print all of the thread's information and stack traces
34.Convert an exception to a String with full stack trace
35.Return stack trace from the passed exception as a stringReturn stack trace from the passed exception as a string
36.Create a new RuntimeException, setting the cause if possible.
37.Create a new Exception, setting the cause if possible.
38.Set the cause of the Exception. Will detect if this is not allowed.
39.Get the stack trace of the supplied exception.
40.Display Stack Trace Information with StackTraceElement
41.A collection of utility methods for manipulating exceptions
42.A frame with a panel for testing various exceptionsA frame with a panel for testing various exceptions
43.Convert Throwable to string
44.Convert the result of Exception.getStackTrace to a String
45.Prints the stack trace of the specified throwable to a string and returns it.
46.Get Stack Trace Element
47.Get stack trace and cause exception
48.Exception Helper
49.Exception Util