In the Java language, exceptions are divided into two categories:
Checked exception: This type of exception must be explicitly thrown in the throws clause or caught within the method. For example, IOException or ClassNotFoundException.
Unchecked exception: This type of exception does not need to be explicitly thrown or caught. For example, NumberFormatException.
When a checked exception is thrown in the run() method of a Thread object, we must catch and handle it because the run() method cannot throw exceptions. When an unchecked exception is thrown in the run() method of the Thread object, the default behavior is to print out the stack trace information on the console and then exit the program.
Fortunately, Java provides us with a mechanism specifically designed to handle unchecked exceptions thrown by Thread objects to avoid program exit.
In this section, we use an example to demonstrate this mechanism.
know it
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 and implement the uncaughtException() method declared in this interface. In this example, the class name is ExceptionHandler, and the uncaughtException() method prints out the exception and the thread information that threw the exception. The code is as follows:
Copy the code code 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: %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());
}
}
2. Implement a class that can throw unchecked exceptions, called Task, implement the Runnable interface, implement the run() method, and specially code a piece of code that can generate unchecked exceptions, for example, convert a string into a number. The code is as follows:
Copy the code code 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:
Copy the code code 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 handling class for unchecked exceptions. Then, start the thread. The code is as follows:
Copy the code code as follows:
Task task = new Task();
Thread thread = new Thread(task);
thread.setUncaughtExceptionHandler(new ExceptionHandler());
thread.start();
5. Run the example and view the results.
know why
The result of the abnormal execution can be seen from the output snippet below. The exception is thrown, then caught by the handler class and the exception information is printed to the console.
Copy the code code as follows:
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 (here specifically refers to an unchecked exception) is not caught, the Java virtual machine checks whether the unchecked exception handling class is set through the corresponding method. If it has been set, uncaughtException( ) method and pass the thread and exception as parameters to the method.
If no processing class is set, the Java virtual machine will print out the stack trace information on the console and then exit the program.
never ending
The Thread class also has a method related to unchecked exception handling. This is the static method setDefaultUncaughtExceptionHandler(), which can set the unchecked exception handling class for all threads in the program.
When an uncaught exception is thrown in a thread, the Java virtual machine looks for exception handling classes from three places:
First, look for the exception handling class from the thread object, and that's what we learned in this section. If it does not exist, the exception handling class is searched from the thread group (ThreadGroup) where the thread is located. This part will be explained specifically later. If it still does not exist, look for the program default exception handling class just mentioned above.
If none of the exception handlers mentioned above exist, the Java virtual machine prints the exception's stack trace information to the console and then exits the program.
Use doctrine
This article is translated from "Java 7 Concurrency Cookbook" (D Gua Ge stole it as "Java7 Concurrency Example Collection") and is only used as learning materials. It may not be used for any commercial purposes without authorization.
Small success
The complete code of the ExceptionHandler class is as follows:
package com.diguage.books.concurrencycookbook.chapter1.recipe8;
/**
* Unchecked 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 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());
}
}
Complete code of Task class
Copy the code code as follows:
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 of Main class
Copy the code code as follows:
package com.diguage.books.concurrencycookbook.chapter1.recipe8;
/**
* Main class of 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();
}
}