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

Uncaught Exceptions ----《Pro_Java_8_Programming_(3rd_edition)》

2016-01-24 11:13 323 查看

Uncaught Exceptions

As mentioned earlier, a thread dies when it exits the run() method of the Runnable object with which it’s

associated. In most cases, this will occur when the thread has executed all the code within that method,

but it can also occur if an exception is thrown that’s not caught. For example, NullPointerException is

perhaps the most common exception that’s encountered by Java programmers, and it isn’t typically caught

and handled because there’s usually no way for the application to recover when a NullPointerException

is thrown. Assuming that a NullPointerException is thrown during execution of the run() method, either

within that method itself or within other code it calls, and assuming that no attempt is made to catch the

exception, it will cause the thread to die.

By default, an uncaught exception simply causes the thread’s stack trace to be printed before the thread

dies, but you can override this behavior using an uncaught exception handler. How you handle uncaught

exceptions depends upon whether you want to customize the behavior for all threads in a ThreadGroup or

you only want to change the behavior for a single thread. When an uncaught exception occurs for a thread

its getUncaughtExceptionHandler() method is called to determine if it has been assigned an instance of

the UncaughtExceptionHandler interface. If so, that object's uncaughtException() method is called and is

passed a reference to the thread and to the exception that occurred. If, on the other hand, no handler has

been assigned to the thread the uncaughtException() method is called for the ThreadGroup associated with

the thread and, as mentioned before, the behavior defined there is to simply display the stack trace of the

thread for which the exception occurred.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: