Demonstrates exception chaining : Exceptions « Language Basics « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » Language Basics » ExceptionsScreenshots 
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[inew 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 idthrows 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[inew Object[] { null, null };
    fields = tmp;
    // Reursive call with expanded fields:
    return makeField(id);
  }

  public Object getField(String idthrows 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. What happens if a method declares an unchecked exception?
5. Simple demo of exceptionsSimple demo of exceptions
6. Simple demo of exceptions, with finally clauseSimple demo of exceptions, with finally clause
7. ThreadBasedCatcher - Demonstrate catching uncaught exceptions
8. Exception CatcherException Catcher
9. Turning off Checked exceptions
10. Finally is always executedFinally is always executed
11. Demonstrating the Exception MethodsDemonstrating the Exception Methods
12. Further embellishment of exception classesFurther embellishment of exception classes
13. The finally clause is always executedThe finally clause is always executed
14. Your own Exception classYour own Exception class
15. Catching exception hierarchiesCatching exception hierarchies
16. How an exception can be lost
17. Exception in main method
18. Ignoring RuntimeExceptionsIgnoring RuntimeExceptions
19. Demonstrating fillInStackTrace()Demonstrating fillInStackTrace()
20. Rethrow a different object from the one that was caughtRethrow a different object from the one that was caught
21. Inheriting your own exceptionsInheriting your own exceptions
22. Overridden methods may throw only the exceptions
23. Throw Exception OutThrow Exception Out
w___w__w___.___j__a_v___a_2_s_._c_o__m_ | Contact Us
Copyright 2003 - 08 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.