开发者

How to simulate an unhandled exception in Java

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

开发者_如何学CThread.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?


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();
  }
}


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.


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.


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

int i = 1/0;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜