You may also wish to override one or more of these methods in exception classes that you
create.
Exception defines four constructors. Two were added by JDK 1.4 to support chained
exceptions, described in the next section. The other two are shown here:
Exception( )
Exception(String msg)
The first form creates an exception that has no description. The second form lets you specify
a description of the exception.
Although specifying a description when an exception is created is often useful, sometimes
it is better to override toString( ). Here's why: The version of toString( ) defined by Throwable
(and inherited by Exception) first displays the name of the exception followed by a colon, which
is then followed by your description. By overriding toString( ), you can prevent the exception
name and colon from being displayed. This makes for a cleaner output, which is desirable in
some cases.
The following example declares a new subclass of Exception and then uses that subclass
to signal an error condition in a method. It overrides the toString( ) method, allowing a
carefully tailored description of the exception to be displayed.
// This program creates a custom exception type.
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}
This example defines a subclass of Exception called MyException. This subclass is quite
simple: it has only a constructor plus an overloaded toString( ) method that displays the
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home