void myMethod() throws Exception
instead of
void myMethod() throws MyAPIException
void myMethod() throws MyAPIRuntimeException
void myMethod()
where MyAPI represents either a generic API related exception or a specific exception related to the method in question.
The choice of "throws Exception" did not even occur to me as a possibility, but after some digging, I found that some relatively famous libraries actually followed that principle at one point, for example Apache Struts 1.x or Spring MVC.
More modern libraries, like Google Guava, commons-math 3.x, Struts 2.x generally favor MyAPIRuntimeException where MyAPI is actually context-specific. Some old popular libraries declare a checked Exception, for example the HibernateException in Hibernate.
This seems to be a recurring subject on Stackoverflow:
Stackoverflow - Java interface throws Exception best practice
Stackoverflow - What to put in the throws clause of an interface method
But those are quite poor in terms of explanations. The best comments on this subjects are from:
Anders Hejlsberg (C#, Delphi, Turbo Pascal creator) - The Trouble with Checked Exceptions
James Gosling (Java creator) - Failure and Exceptions
This comment from Anders is particularly acute:
"To work around this requirement, people do ridiculous things. For example, they decorate every method with, "
throws Exception
." That just completely defeats the feature, and you just made the programmer write more gobbledy gunk. That doesn't help anybody. "Today I believe the API in question declares "throws Exception"...
No comments :
Post a Comment