您的位置:首页 > 编程语言 > Java开发

java线程中异常的处理 -Java 7 Concurrency Cookbook 读书笔记

2015-11-01 09:53 661 查看

java线程中异常的处理Processing uncontrolled exceptions in a thread

* There are two kinds of exceptions in Java:

*

* Checked exceptions: These exceptions must be specified in the throws clause of a method or caught inside them. For example, IOException or ClassNotFoundException.

*

* Unchecked exceptions: These exceptions don't have to be specified or caught. For example, NumberFormatException.

*

*

* When a checked exception is thrown inside the run() method of a Thread object, we have

* to catch and treat them, because the run() method doesn't accept a throws clause. When

* an unchecked exception is thrown inside the run() method of a Thread object, the default

* behaviour is to write the stack trace in the console and exit the program.

*

* When an exception is thrown in a thread and is not caught (it has to be an unchecked

* exception), the JVM checks if the thread has an uncaught exception handler set by the

* corresponding method. If it has, the JVM invokes this method with the Thread object and

* Exception as arguments.

*

* If the thread has not got an uncaught exception handler, the JVM prints the stack trace in the

* console and exits the program.

*

*

* Fortunately, Java provides us with a mechanism to catch and treat the unchecked exceptions

* thrown in a Thread object to avoid the program ending.

*

* @see UncaughtExceptionHandler

*

*

* The Thread class has another method related to the process of uncaught exceptions. It's the

* static method setDefaultUncaughtExceptionHandler() that establishes an exception

* handler for all the Thread objects in the application.

* When an uncaught exception is thrown in Thread, the JVM looks for three possible handlers

* for this exception.

* First, it looks for the uncaught exception handler of the Thread objects as we learned in this

* recipe. If this handler doesn't exist, then the JVM looks for the uncaught exception handler

* for ThreadGroup of the Thread objects as was explained in the Processing uncontrolled

* exceptions in a group of threads recipe. If this method doesn't exist, the JVM looks for the

* default uncaught exception handler as we learned in this recipe.

* If none of the handlers exits, the JVM writes the stack trace of the exception in the console

* and exits the program.

*/

https://github.com/sdcuike/book-reading/blob/master/Java7-Concurrency-Cookbook/src/main/java/com/doctor/ch01/ProcessingUncontrolledExceptionsInATthread.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: