Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 365
Martin Wiboe Avatar asked Jun 14 '10 22:06

Martin Wiboe


People also ask

How do you throw an unhandled exception in Java?

The first throw statement i.e throw new NullPointerException("demo"); is handled by the following catch block, but the second throw statement i.e. throw e; is unhandled by the demoproc() method. Now this works here and the above code compiles successfully because NullPointerException is a runtime/ unchecked exception.

What is unhandled exception in Java?

Unhandled exceptions cause the current thread to exit. If the current thread is the thread in which main was executed, the shutdown sequence will be initiated without waiting for non-daemon threads to exit. The JVM will exit with a non-zero exit code.

How do you create an exception in Java?

To create the exception object, the program uses the throw keyword followed by the instantiation of the exception object. At runtime, the throw clause will terminate execution of the method and pass the exception to the calling method.

How do you handle an unhandled exception in the thread?

Uncaught exception handler will be used to demonstrate the use of exception with thread. It is a specific interface provided by Java to handle exception in the thread run method. There are two methods to create a thread: Extend the thread Class (java.


2 Answers

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();
  }
}
like image 100
Matthew Flaschen Avatar answered Oct 15 '22 05:10

Matthew Flaschen


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.

like image 6
Dr. Snoopy Avatar answered Oct 15 '22 05:10

Dr. Snoopy