How to simulate an unhandled exception in Java

0 votes
asked Jun 14, 2010 by martin-wiboe

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?

4 Answers

0 votes
answered Jun 14, 2010 by matthew-flaschen

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();
  }
}
0 votes
answered Jun 14, 2010 by matias-valdenegro

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.

0 votes
answered Jun 14, 2010 by eyal-schneider

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.

0 votes
answered Sep 15, 2017 by amir-hossein-ghasemi

just add this code and you'll get unhandled exception without lint error:

int i = 1/0;
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...