Java Thread catch uncaught exceptions in a thread

Introduction

Java Thread catch unchecked exceptions in a thread

Java can catch and treat the unchecked exceptions thrown in a Thread object to avoid the program ending.

If the thread has not got an uncaught exception handler, Java prints the stack trace in the console and exits the program.


import java.lang.Thread.UncaughtExceptionHandler;

public class Main {
  public static void main(String[] args) {
    // Creates the Task
    Task task = new Task();
    // Creates the Thread
    Thread thread = new Thread(task);
    // Sets the uncaught exception handler
    thread.setUncaughtExceptionHandler(new ExceptionHandler());
    // Starts the Thread
    thread.start();//from ww  w .jav  a2s  .  com

    try {
      thread.join();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.printf("Thread has finished\n");
  }
}

class ExceptionHandler implements UncaughtExceptionHandler {
  @Override
  public void uncaughtException(Thread t, Throwable e) {
    System.out.printf("An exception has been captured\n");
    System.out.printf("Thread: %s\n", t.getId());
    System.out.printf("Exception: %s: %s\n", e.getClass().getName(), e.getMessage());
    System.out.printf("Stack Trace: \n");
    e.printStackTrace(System.out);
    System.out.printf("Thread status: %s\n", t.getState());
  }

}

class Task implements Runnable {

  @Override
  public void run() {
    // The next instruction always throws and exception
    int numero = Integer.parseInt("ASDF");
  }

}



PreviousNext

Related