I realize that there has been ample discussion of the relative merits of checked exceptions versus unchecked exceptions in Java, and it is not my intention to revisit the entire debate.
Rather, I would like to ask a very specific question that came to mind as I was reading Joshua Bloch's Effective Java, 2nd Edition. As I was reading, I noticed that in Item 59 ("Avoid unnecessary use of checked exceptions") Joshua gives an example in the Java API where a checked exception is used. Specifically, in Object
:
protected Object clone()
throws CloneNotSupportedException
...and then argues that it should have been an unchecked exception instead.
If the programmer using the API can do no better, an unchecked exception would be more appropriate. One example of an exception that fails this test is CloneNotSupportedException. It is thrown by Object.clone, which should be invoked only on objects that implement Cloneable (Item 11). In practice, the catch block almost always has the character of an assertion failure. The checked nature of the exception provides no benefit to the programmer, but it requires effort and complicates programs.
I then looked to see if he had an example of the converse, but I could not find one.
So I would like to ask if someone can give an example API in Java that uses an unchecked exception, but where a checked exception would have been a better choice, and explain why. A real-world example would be preferable, but I'm open to a contrived example if that would illustrate matters just as well.
Edit: To those who have voted to close this as non-constructive, I want to make it clear that I am not looking for opinion, debate, argument, or extended discussion. Nor am I taking a poll. Rather I am looking for references to examples that yield a clear analysis of how the benefits outweigh the costs. (Implicit in that is acknowledging that there are costs.) That said, I am skeptical about whether the nature of this question makes that possible. I reckon if Jon Skeet can't do it, it's unlikely that it can be done. So maybe you're right. Close if you must.
Edit: Though I'm unmoved by the response, I'm going to award this to Jon just for my accept-rate.
Yup, easily: Integer.parseInt
throws NumberFormatException
which is unchecked.
However, if you're ever parsing potentially-bad data, you should definitely consider catching the exception - you may very well be able to ignore that data, or perhaps report it and move on. It's not like Java has an equivalent of .NET's Int32.TryParse
which lets you easily ignore bad data. Basically you need to know that you need to catch the exception, without the provocation of the compiler. Grr.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With