advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Tutorials : Using Chained Exceptions in JDK 1.4 :

Chaining the Exceptions

This is where exception chaining comes in handy. In JDK 1.4 we can attach an "old" exception to a "new" one, and by doing so keep them both. It's simply done by adding the old exception to the exception constructor. We can modify the "throws" statement to this:

throw new RuntimeException("w contains [" + toString(w) + "]", r);

This time we'll get this "double" traceback:

java.lang.RuntimeException: w contains []
  at hansen.playground.GetMean2.mean(GetMean2.java:15)
  at hansen.playground.GetMean2.main(GetMean2.java:7)
Caused by: java.lang.RuntimeException: Division by zero
  at hansen.playground.GetMean2.divide(GetMean2.java:26)
  at hansen.playground.GetMean2.mean(GetMean2.java:13)
  ... 1 more
Exception in thread "main"

Now the tracebacks contain data for both the exceptions that we have thrown. This makes it possible for every method in the calling chain to supply whatever information which could be of value for debugging. The phrase "… 1 more" simply means that the next line in the traceback is the same as the last in the traceback above (line 7 in main).

In JDK 1.4 SUN has added chained exceptions by adding the "cause" property which can hold an instance of a Throwable. The idea is that if you decide to throw an exception after having caught another exception then simply save this exception--the "cause"-- as part of the new exception. It's easiest to add the cause with a constructor: 

Pre jdk 1.4

New in jdk 1.4

Throwable()

Throwable(Throwable cause)

Throwable(String message)

Throwable(String message, Throwable cause)

You may also add the cause with this method call: initCause (Throwable cause). There is a corresponding method call: getCause() which returns the previous throwable.

Getting Data from the Stack Trace

As you can see from the example above, the tracebacks from the exceptions will often contain duplicate information. To get rid of the superfluous information you can decide to produce your own traceback. The Throwable class in JDK 1.4 also contains a new method--getStackTrace--that returns an array of StackTraceElement's. Each element contains information from one line of the traceback: for example the names of the class and method and also the line number where the error occurred.

As an exercise we'll print the whole array to see what it contains. We therefore insert another try-catch block in "main", and let the catch-part call our own traceback method:

. . . (in main) . . .
try {
  f = new GetMean3().mean(v);
} catch (RuntimeException r) {
  printExceptionChain(r);
  System.exit(1);
} 
. . .

The print method could be programmed like this:

private static void printExceptionChain(Throwable thr) {
  StackTraceElement[] s;
  Throwable t = thr;
  System.out.println("Exception chain (top to bottom):");
  while (t != null) {
    System.out.println("-------------------------------");
    System.out.println(t.toString());
    s = t.getStackTrace();
    for (int i = 0; i < s.length; i++) {
      StackTraceElement si = s[i];
      System.out.println(i + ": " + si.toString());
    }  
    t = t.getCause();
  }  
}

See the whole program here. When running the program we'll get this printed out:

Exception chain (top to bottom):
-------------------------------
java.lang.RuntimeException: w contains []
0: hansen.playground.GetMean3.mean(GetMean3.java:39)
1: hansen.playground.GetMean3.main(GetMean3.java:9)
-------------------------------
java.lang.RuntimeException: Division by zero
0: hansen.playground.GetMean3.divide(GetMean3.java:50)
1: hansen.playground.GetMean3.mean(GetMean3.java:37)
2: hansen.playground.GetMean3.main(GetMean3.java:9)

Note that for every exception thrown there'll be a traceback, and that there is some redundancy in the information printed. Also note that the first line ("0:") gives the line number of the throw-statement; the line numbers following point to the failing methods.

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Avaya Developer Showcase
 MSDN Spotlight
 PHP for Windows Showcase
XML error: undefined entity at line 34
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

IBM Brings Developers Into the Cloud
Apache at 10: You Can't Buy Us
Microsoft's CodePlex Foundation Moving Forward
Apple Claims 100,000 Apps, Google Analyzes Them
Nokia Latest to Play Opera Mobile 10 Browser
PayPal Opens Up Payment Platform to Devs
Ubuntu Linux 9.10 'Karmic Koala' Starts Its Climb
IBM Links Rational Developer Tools, Tivoli Apps
Libraries Give Vista Apps a Windows 7 Look
Ubuntu: The 'Default Alternative' to Windows?

Delivering Web-based Embedded Fonts in CSS 3
Adobe Helps PHP Developers Create Rich Internet Applications
Java Developers Finding a Home at Adobe Flex
Virtualization Delivers a Dynamic Infrastructure
Consuming XML Web Services in iPhone Applications
Build a More Agile Business with IBM
POJO-Based Solutions for LDAP Access: One Good, One Better
IBM Offers Enhanced Measurement and Management for Energy Usage
IBM Helps Transformation to an Information-Based Enterprise
Top Five Touch UI-Related Design Guidelines

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs