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

来源:互联网 发布:做贝斯四线谱软件 编辑:程序博客网 时间:2024/06/05 15:56

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.
0 0
原创粉丝点击