Why do some APIs simply throw Exception

exceptionsreadability

This year I started using several Third-Party-Libraries (all open source) and I noted that some throw exceptions in a proper way (i.e. declaring exactly which checked Exceptions can be thrown by a method in the method signature), while others just declare throws Exception, which generally makes it more difficult to catch and properly handle them. I think examples for the "good" ones are the Apache libraries (at least these I use like commons-cli), examples for the "bad" ones are WEKA and the Simple Framework XML. (All my examples are Java examples because I primarly use Java, but my question holds in general.)

So, an obvious reason for the "bad" behavior is that it is easier/faster to program and may look nicer than a throws ThisException, ThatException, AnotherException. But is this really all reason there is to it?

This is not about checked/unchecked exceptions. This is about readability and that I have to deal with an exception that simply has the basic Exception type with no clarifying information. If it would be an unchecked exception, maybe always the same, I would be very happy as long as the documention clarifies why it happened. In addition, e.g. the Simple Framework API uses special exceptions inside, but all that is propagated to the top level is "Exception".

What are the reasons for this behaviour in general?

Best Answer

There is no good reason to do this. And in fact declaring a method as throws Exception makes it difficult to use. This is covered by this "example" in the Java Language documentation tree over on StackOverflow:

The short version is that if you declare a method as throws Exception, any code that calls that method must either catch (Exception ...) or have its own throws Exception clause. If you do this consequences are as follows:

  • You have nullified the compiler's ability to tell you when you haven't handle specific checked exceptions.

  • Someone reading your API code has no easy way to find out what checked exceptions might actually be thrown or propagated by the method.