views:

105

answers:

4

Hi,

I am creating some multi-threaded code, and I have created a JobDispatcher class that creates threads. I want this object to handle any unhandled exceptions in the worker threads, and so I am using

Thread.setUncaughtExceptionHandler(this);

Now, I would like to test this functionality - how can I generate an unhandled exception in the run() method of my worker object?

Thanks,

Martin

+5  A: 

Just throw any exception.

E.g.:

throw new RuntimeException("Testing unhandled exception processing.");

Complete:

public class RuntimeTest
{
  public static void main(String[] a)
  {
    Thread t = new Thread()
    {
      public void run()
      {
        throw new RuntimeException("Testing unhandled exception processing.");
      }
    };
    t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
    {
      public void uncaughtException(Thread t, Throwable e)
      {
        System.err.println(t + "; " + e);
      }
    });
    t.start();
  }
}
Matthew Flaschen
Eclipse won't let me compile when I do this - it insists I surround with try/catch. Do you know how to change this behavior?
Martin Wiboe
It should compile. Looks like some Eclipse-specific extra check.
Matthew Flaschen
Eclipse might complain if you have other code in a method after the throwing of the exception, make it the only/last line in the method it is in.
Alb
@Martin, you should be able to right click on the line where the unhandled exception is occurring and tell eclipse to ignore it.
Lirik
Use `if (true) throw new RuntimeException("Melp");` else Eclipse/javac will indeed complain about unreachable code. Note that there's a subtle compiler difference between **runtime** exception and "normal" exception.
BalusC
@Balus, pretty sure this is an Eclipse-specific issue. I posted an example that always throws, has no conditional, and compiles in javac.
Matthew Flaschen
+2  A: 

What's the problem with just throwing an exception:

throw new Exception("This should be unhandled");

Inside your run method. And of course, not catching it. It should trigger your handler.

Matias Valdenegro
A: 

Just throw an exception from the run() method, outside of any try/catch block.

BoltClock
A: 

You should throw some unchecked exception. An unchecked exception does not require your code to handle it, and is therefore a good candidate to make all the way down the call stack.

You can choose RuntimeException for example, or even something like AssertionError, if you want to minimize the chances that some part of the code catches the exception and handles it before it reaches your handler.

Eyal Schneider