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 your own exception classes in Java :
Contents
Using your own exception classes in Java
Linking the Exception classes
New formatting routines in MyException

Linking the Exception classes

One of the things which are saved in our exception class is the exception it has just caught. By doing this we'll get a linked list of exception classes, that can document the calling sequence "top->a->b ". Java will as default produce a trace back of calling methods when an exception is thrown, but it does not contain any application data. Our own trace back will contain this.

So now it's time to show our own exception class--it's a "minimal" exception class--we'll add some more to it later, and you may want to enhance it further:

package playground;
import java.io.*;

public class MyException extends Exception {
  private int id; // a unique id
  private String classname; // the name of the class
  private String method; // the name of the method
  private String message; // a detailed message 
  private MyException previous = 
  	null; // the exception which was caught
  private String separator = "\n"; // line separator
  
  public MyException(int id, String classname, String method, 
    String message, MyException previous) {
    this.id        = id;
    this.classname = classname;
    this.method    = method;
    this.message   = message;
    this.previous  = previous;
  }  
    
  public String traceBack() {
    return traceBack("\n");
  }  

  public String traceBack(String sep) {
    this.separator = sep;
    int level = 0;
    MyException e = this;
    String text = line("Calling sequence (top to bottom)");
    while (e != null) {
      level++;
      text += line("--level " + level + "--------------------------------------");
      text += line("Class/Method: " + e.classname + "/" + e.method);
      text += line("Id          : " + e.id);
      text += line("Message     : " + e.message);
      e = e.previous;
    }  
    return text;
  }  

  private String line(String s) {
    return s + separator;
  }  

}

The member variables in the class--which are used in the constructor--have these meanings:

id

A number that is unique within the class which throws the exception. It is used to identify the place in the class where the error was caught, and--if appropriate--it can also be used by the calling method to identify the error.

classname

The name of the class that caught the error.

method

The name of the method that caught the error.

message

A string of useful data. First of all a message which describes the situation, but also values of variables within the class or method.

previous

An instance of "MyException", or null if this is the first in the linked list.

 The methods in MyException are these:

traceBack()

Will produce a trace back of the calling methods including the data stored in the exception classes. The "newline" character is used as line separator.

traceBack(String sep)

Will produce a trace back with the given string as line separator. If the trace back is used in an HTML page you would use "<BR>" as line separator.

line(String s)

A utility method used by traceBack.

Step 1: Who throws the first exception?

Two situations exist:

a: You--the programmer--throws the first exception. You would do this if you have detected a situation which you consider fatal, and you decide to halt execution. Let's consider an example using a class "Person" with a method "getSalary", which fails. You now report the error like this:

throw new MyException(
  1, "Person", "getSalary", 
  "Trying to get a salary, but no person was specified",null); 

Since you have not caught an exception the last parameter is simply null.

b: Another one has thrown the first exception, and we assume that it's not a "MyException". As an example we again consider the class "Person" and assume that the method "read" has caught an exception. This is handled like this:

catch (Exception e) {
  throw new MyException(4, "Person", "read", e.toString(), null);
}

As the general rule you may use "toString" to save exception information in our own instance of MyException. But you may of course enter any useful information you like for the "message" member variable.

If we have caught an exception where toString will not give us all the data available, we could first create an instance of our own exception class and store data in it. Then we could create another instance which would link to the first one. The SQLException class is good example of this:

catch (java.sql.SQLException sqle) {
  MyException my = new MyException(999, "Person", "read", 
    "SQLException. State/error code: " + 
  sqle.getSQLState() + "/" + sqle.getErrorCode(), null);
  throw new MyException(3, "Person", "read", sqle.toString(), my);
}

Since "read" is now throwing a MyException it must be declared like this:

public void read() throws MyException . . . 

Step 2: Catching our own exception

In order for our scheme to work the caller of the method that's now throwing an instance of MyException must be prepared to catch it. Let's look at an example. Below is shown some of the code in a method called "getAllSalaries" in a class called "Stats":

Person p = new Person();
p.setPersonId(id);
try {
  p.read();
  s += p.getSalary();
}  
catch (MyException e) {
  throw new MyException(1, "Stats", "getAllSalaries", 
    "Could not get salary for " + id, e);
}

So the technique is this: we have called a method which fails, and what we should do now is to give "our point of view" of the situation, which we in this case can do by saving the id of the "person" we are processing. If we have other information--and we'll typically have much more information in a more realistic case--we should of course save it too. It's extremely important to consider what the useful information is and have it saved in the exception class. As a programmer you should ask yourself: What information would I like to see if my program crashes right here?

Step 2 should be repeated for each method in the calling sequence, and each method will add (at least) one instance of MyException to the linked list of classes.

Step 3: Using the contents of our exception classes

When we reach the top level the chaining of exceptions stops. So now it's time to use the "traceBack" method in "MyException". By calling this we'll get a nicely formatted trace back of what has happened. It could look like this:

Calling sequence (top to bottom)
--level 1--------------------------------------
Class/Method: SalaryServlet/doGet
Id : 7
Message : Trying to get the total salary for employees
--level 2--------------------------------------
Class/Method: Stats/getAllSalaries
Id : 1
Message : Could not get salary for Lincoln
--level 3--------------------------------------
Class/Method: Person/read
Id : 3
Message : java.sql.SQLException: [HANSEN]Invalid object name 'xEMPLOYEE'.
--level 4--------------------------------------
Class/Method: Person/read
Id : 999
Message : SQLException. State/error code: S0002/208

In this scenario a servlet has been invoked, which calls method getAllSalaries, which calls read, which gets an SQL exception. The last level is the MyException instance we build to contain the SQL information. Level 3 above shows that we are using an incorrect table name, which probably should be EMPLOYEE. Note that level 2 shows the name of the person we are dealing with.

The trace also shows that the servlet has built its own instance of MyException before calling traceBack. This is an option if the servlet has important information to add.

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 DevConnect Center
 Service Component Architecture/Service Data Objects Solution Center
 Intel Go Parallel Portal
 Internet.com eBook Library
 IBM Software Construction Toolbox
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 53
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%.

Windows 7: It's Not Just a Codename Anymore
Microsoft Shines Silverlight on Eclipse
OpenOffice Hits 3.0: Can It Challenge Microsoft?
Get Ready for Microsoft's 'Oslo' Modeling Tool
Latest Linux Hits Networking Flaws
Metasploit 3.2 Offers More 'Evil Deeds'
'Thank You Apple. Seriously.'
The Buzz: BlackBerry App Store Seen Next
Is .NET on Linux Finally Ready?
Red Hat Takes on HPC Market, Microsoft

Intel Sees Fewer Power Cords in Your Future
F# 101
Use Explicit Conversion Functions to Avert Reckless Implicit Conversions
Polyglot Programming: Building Solutions by Composing Languages
Automated testing for .NET by Ben Hall
"Supply Chain" SOA with SKOS
Service Component Architecture in Real Life
C++Ox: The Dawning of a New Standard
Getting Started with Virtualization
Master Complex Builds with MSBuild

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



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Microsoft Article: BitLocker Encryption on Windows Server 2008
Go Parallel Article: Intel Thread Checker, Meet 20 Million LOC
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Tripwire Whitepaper: Seven Practical Steps to Mitigate Virtualization Security Risks
Internet.com eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES