Hacker News new | past | comments | ask | show | jobs | submit login

The biggest problem we have dealing with checked exceptions in Java is that it complicates interface inheritance when working with third-party class libraries. What do you do if you have to write a concrete class to implement an interface, but the interface's methods don't declare the exceptions you need? The interface isn't under your control, and the interface method signatures can't be changed anyway due to backward compatibility concerns.

What I usually do is cheat by catching the checked exception within the method, and then throw it again by using exception chaining to wrap it into an unchecked exception (RuntimeException). But it's hard to see that as a good solution.




"What I usually do is cheat by catching the checked exception within the method, and then throw it again by using exception chaining to wrap it into an unchecked exception (RuntimeException). But it's hard to see that as a good solution."

By throwing RuntimeException you're saying "don't catch this," which I agree is a bad thing, but any other kind of unchecked exception would be just as bad. You implement a third-party interface so other people's code can call methods on your object. If you throw exceptions they don't expect, then they have no chance of catching them anyway, so what's the difference?

Checked exceptions are just another way of specifying the behavior of an object so it can be handled predictably without knowing its precise type. If a method doesn't let you throw an exception indicating failure, then the method isn't supposed to fail, or it's supposed to report failure another way. If that isn't reasonable for your implementation, then the library isn't suitable for your needs. It isn't much different from the case where a method lacks arguments that you need, or has a return type that is too restrictive for your needs. If you can't adapt your code to fit the interface, you can't use it.


Ha ha. Nice theory, but sometimes in the real world you have no choice but to use a particular third-party interface even if it isn't perfectly suitable.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: