How to do it...

Follow these steps to implement the example:

  1. First of all, we have to implement a class to treat unchecked exceptions. This class must implement the UncaughtExceptionHandler interface and implement the uncaughtException() method declared in this interface. It's an interface enclosed in the Thread class. In our case, let's call this class ExceptionHandler and create a method to write information about Exception and Thread that threw it. The following is the code:
        public class ExceptionHandler implements UncaughtExceptionHandler { 
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.printf("An exception has been captured ");
System.out.printf("Thread: %s ",t.getId());
System.out.printf("Exception: %s: %s ",
e.getClass().getName(),e.getMessage());
System.out.printf("Stack Trace: ");
e.printStackTrace(System.out);
System.out.printf("Thread status: %s ",t.getState());
}
}
  1. Now implement a class that throws an unchecked exception. Call this class Task, specify that it implements the Runnable interface, implement the run() method, and force the exception; for example, try to convert a String value into an int value:
        public class Task implements Runnable { 
@Override
public void run() {
int numero=Integer.parseInt("TTT");
}
}
  1. Now implement the main class of the example. Implement a class called Main with its main() method:
        public class Main { 
public static void main(String[] args) {
  1. Create a Task object and Thread to run it. Set the unchecked exception handler using the setUncaughtExceptionHandler() method and start executing the thread:
            Task task=new Task(); 
Thread thread=new Thread(task);
thread.setUncaughtExceptionHandler(new ExceptionHandler());
thread.start();
}
}
  1. Run the example and see the results.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.119.106