Java Exception Classes | Linking the Classes

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.

 

 1 
About | Sitemap | Contact