Java concurrent programming example of eight: handles unchecked exceptions for threads

  • 2020-04-01 03:33:06
  • OfStack

In the Java language, exceptions are divided into two categories:

Abnormal condition: Such exceptions must be explicitly thrown in the throws clause or caught within the method. For example, IOException or ClassNotFoundException.
Non-detected abnormal: Such exceptions do not need to be explicitly thrown or caught. For example, NumberFormatException is an exception.

When a checked exception is thrown in the Thread object's run() method, we must catch and process it because the run() method cannot throw an exception. When a non-checked exception is thrown in the Thread object's run() method, the default behavior is to print out the stack trace at the console and exit the program.

Fortunately, Java provides a mechanism for handling unchecked exceptions thrown by Thread objects to avoid program exits.

In this section, we use an example to demonstrate this mechanism.

learning

Follow the steps shown below to implement our example.

1. First, we need to implement a class for handling unchecked exceptions. This class must implement the UncaughtExceptionHandler class, which implements the uncaughtException() method declared in the interface. In this case, the class named ExceptionHandler, uncaughtException() method prints out the exception and the thread that threw it. The code is as follows:


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

2. Implement a class called Task that can throw an unchecked exception, implement the Runnable interface, implement the run() method, and intentionally code a piece of code that can generate an unchecked exception, for example, by converting a string to a number. The code is as follows:


public class Task implements Runnable {
    @Override
    public void run() {
        int numero = Integer.parseInt("diguage.com");
    }
}

3. Create the Main class of the program, the Main class, and then implement the Main () method. The code is as follows:


public class Main {
    public static void main(String[] args) {

4. Create a Task object and create a Thread object to execute it. Use the setUncaughtExceptionHandler () method to set the client exception handler class. Then, start the thread. The code is as follows:

Task task = new Task();
Thread thread = new Thread(task);
thread.setUncaughtExceptionHandler(new ExceptionHandler());
thread.start();

5. Run the example to see the results.

Know why

You can see the result of the exception execution from the output snippet below. The exception is thrown, which is then caught by the processing class and printed to the console.


An exception has been captured
Thread: 9
Exception: java.lang.NumberFormatException: For input string: "diguage.com"
Stack Trace:
java.lang.NumberFormatException: For input string: "diguage.com"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:492)
    at java.lang.Integer.parseInt(Integer.java:527)
    at com.diguage.books.concurrencycookbook.chapter1.recipe8.Task.run(Task.java:13)
    at java.lang.Thread.run(Thread.java:722)
Thread status: RUNNABLE Process finished with exit code 0

When a thread throws an exception and the exception (in this case, an unchecked exception) is not caught, the Java virtual machine checks to see if the unchecked exception handling class is set through the corresponding method, and if so, calls the uncaughtException() method, passing the thread and exception as parameters to the method.

If the processing class is not set, the Java virtual machine prints out the stack trace in the console and exits the program.

endless

The Thread class also has a method related to non-checked exception handling. This is a static method setDefaultUncaughtExceptionHandler (), the method can set all of the threads in a program of b. exception handler class.

When an uncaught exception is thrown in a thread, the Java virtual machine looks for the exception handler class in three places:

First, look for the exception handler class from the thread object, which is what we learned in this section. If it does not, the exception handler class is found in the ThreadGroup where the thread resides. We'll talk more about that in the future. If it still does not exist, then look for the program default exception handling class mentioned above.

If none of the exception handling mentioned above exists, the Java virtual machine prints the stack trace information for the exception to the console and exits the program.

si

This article is a translation from the Java7 Concurrency Cookbook (D jago to Java7 Concurrency examples) and is intended for use only as a learning material. Not to be used in any commercial activities without authorization.

Small has becomes

The complete code for the ExceptionHandler class


package com.diguage.books.concurrencycookbook.chapter1.recipe8; /**
 * Undetected exception handling class
 * Date: 2013-09-22
 * Time: 23:11
 */
public class ExceptionHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.printf("An exception has been capturedn");
        System.out.printf("Thread: %sn", t.getId());
        System.out.printf("Exception: %s: %sn", e.getClass().getName(),
                e.getMessage());
        System.out.printf("Stack Trace: n");
        e.printStackTrace(System.out);
        System.out.printf("Thread status: %sn", t.getState());
    }
}

Complete code for the Task class


package com.diguage.books.concurrencycookbook.chapter1.recipe8; /**
 * Exception generation class
 * Date: 2013-09-22
 * Time: 23:18
 */
public class Task implements Runnable {
    @Override
    public void run() {
        int numero = Integer.parseInt("diguage.com");
    }
}

The complete code for the Main class


package com.diguage.books.concurrencycookbook.chapter1.recipe8; /**
 * The main class for the example
 * Date: 2013-09-22
 * Time: 23:20
 */
public class Main {
    public static void main(String[] args) {
        Task task = new Task();
        Thread thread = new Thread(task);
        thread.setUncaughtExceptionHandler(new ExceptionHandler());
        thread.start();
    }
}


Related articles: