Why Is InterruptedException a Checked Exception?
When working with threads in Java, dealing with InterruptedException seems to be a particular thorn in my side. I appreciate the fact that it's thrown when my threads are terminated, and thus offers me a chance to cleanup. What seems odd to me is that it's not an unchecked exception.
This creates the following problems: a) If I want to use an existing framework in my threaded app, I'm forced to convert it to an exception the framework interface accepts. Thus the framework generally misinterprets it instead of either cleaning up or propagating it as it should.
b) Unless InterruptedException is rigorously declared for every call in the stack (and it's usually not because of a) ), it's difficult to cleanly shutdown.
If InterruptedException were instead unchecked, it seems that it would have a much higher likely hood of being used properly and resulting in clean shutdown of threads and apps in general. Why isn't it?
Interruption is supposed to be cooperative. I think the designers wanted to avoid a situation where you could blow away a thread by interrupting it, where the thread didn't have code to handle that eventuality. The intention seems to have been to make the Runnable code explicitly decide how to handle interruption. A lot of framework or language code seems to be about deciding whose responsibility something should be, and trying to make the correct usage apparent, in order to minimize how badly users get burned. This is one of those judgment calls.
With InterruptedException being checked, the worst case is that the exception is caught, but in a way that isn't awfully useful. (Actually the absolute worst case is the interrupt flag is not restored, leaving any following code in the thread unaware that the interruption happened.) If InterruptedException was unchecked (or if you wrap it in a RuntimeException, as shown in the article linked in the comments), the exception could go unhandled and proceed to terminate the thread, which could be really bad if the thread was not at a stopping place.
Toy examples and simple code would work better with unchecked InterruptedExceptions; nobody would bother with catching the exception and it would just work. However, in real code doing substantial work this was probably considered detrimental.
Making the exception checked is an attempt to ensure that the developer knows the exception can be thrown so that the developer can avoid the situation where the exception gets thrown in the middle of work the thread is doing, potentially leaving the work partially-done in a bad state.
链接地址: http://www.djcxy.com/p/83754.html上一篇: 如何知道.pem文件是否包含公钥或私钥?
下一篇: 为什么中断异常检查异常?