The first exception handling policy.
- By Chi-keong Iong
- August 16, 2001
Java To Go!
Exception handling using the VISITOR pattern
by Chi-keong Iong
Listing 2. The first exception handling policy.
class VisitorException
extends Exception
{
// an optional object reference to
// record the original thrower
private Object thrower=null;
public VisitorException()
{ super(); }
public VisitorException(String s)
{ super(s); }
public VisitorException(Object o)
{ super(); thrower = o; }
public VisitorException(String s,
Object o)
{ super(s); thrower = o; }
void visit(A a) throws Exception
{
System.out.println(
“A is visited.”);
throw this; // Rethrow!
}
void visit(B b) throws Exception
{
System.out.println(
“B is visited.”);
throw this; // Rethrow!
}
void visit(C c) throws Exception
{
System.out.println(
“C is visited.”);
throw this; // Rethrow!
}
void visit(Object o)
throws Exception
{
// Default behavior for all
// undefined visited classes
System.out.print(
o.getClass().getName()
+ “ is visited”);
if (thrower != null)
System.out.print(
“, the original thrower is “ +
thrower.getClass().getName());
System.out.println(“.”);
// Stop propagating the
// exception...
}
}