Re: Default exception handler
dgront wrote:
Dear group,
quite recently I learned about UncaughtExceptionHandler feature in
JAVA 5. For me this is very appealing, because I have a lot of methods
that throw overall a few types of exceptions. So far I had to copy a
relevant try{} catch{} fragment which is common for most of the cases.
Now I plan to register a UncaughtExceptionHandler (my applications
runs always in a single thread) and to hide all the common code inside
uncaughtException() inherited from Thread.UncaughtExceptionHandler.
This works perfect, but a new problem appeared:
In typical try{} catch{} block I can handle different types of
exceptions by separate close{} blocks. Method uncaughtException()
receives an object of type Throwable as an argument. Currently, to
handle different exceptions types separately, I use instanceof clause:
public class MyHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
if (e instanceof IllegalMatrixArgumentException) {
}
System.err.println(t + " threw exception: " + e);
}
[... and then ...]
> Sorry, I accidentally submitted before finishing.
>
> So I use instanceof to find out what kind of exception happened. This
> looks tedious and I am looking for a more elegant solution. Do you
> have any ideas?
>
> The best what I found is to extend RuntimeException (I handle only
> these by my default handler) and to add an enum field to each
> exception. Then I will be able to dispatch exceptions within a switch
> clause.
>
> Can you find a better idea? Or maybe instanceof is good enough, since
> exceptions appear very rarely.
You may have missed an important point: the default
exception handler is a "last gasp" handler that runs just
before an uncaught exception destroys a thread. When the
DEH's uncaughtException() method returns, the thread is
dead, finis, kaput. The uncaughtException() method is not
a catch block.
If you want to catch all exceptions in one of your
threads, just write a try/catch in the run() method:
public void run() {
try {
actualRun();
}
catch (IOException ex) {
...
}
catch (IncompleteAnnotationException ex) {
...
}
catch (ExceptionThatProvesTheRule ex) {
...
}
catch (Throwable t) {
...
}
}
.... where actualRun() is all the stuff that used to be
in run().
--
Eric.Sosman@sun.com