I have a pet peeve in Java, and it's methods that use the java.lang.Exception class in the throws clause.
For example
public void doSomething() throws Exception {
}
This forces callers of the doSomething method to either catch the raw Exception, or add it to throws clause of the consuming method. I think that this encourages developers to do the wrong thing. If you're going to use checked exceptions, then callers should only be catching specific exceptions that can be handled. Otherwise, the exception should propagate up the call stack, potentially terminating the thread if no one handles the exception.
Throws clauses are part of the specification of your method. If you're going to use checked exceptions, wouldn't it be nice if the caller could see the explicit list of exceptions to be handled? From a contract perspective, there's no value in specifying that your method can throw any Exception. You're better off removing the throws Exception clause, and just throwing a RuntimeException instead.
throws Exception is just cluttering up your code, adding no value, potentially adding negative value since it encourages catching too many exceptions.
Instead, make throws clause contain specific Exceptions, or better yet remove it altogether and use unchecked exceptions.
For example
public void doSomething() throws Exception {
}
This forces callers of the doSomething method to either catch the raw Exception, or add it to throws clause of the consuming method. I think that this encourages developers to do the wrong thing. If you're going to use checked exceptions, then callers should only be catching specific exceptions that can be handled. Otherwise, the exception should propagate up the call stack, potentially terminating the thread if no one handles the exception.
Throws clauses are part of the specification of your method. If you're going to use checked exceptions, wouldn't it be nice if the caller could see the explicit list of exceptions to be handled? From a contract perspective, there's no value in specifying that your method can throw any Exception. You're better off removing the throws Exception clause, and just throwing a RuntimeException instead.
throws Exception is just cluttering up your code, adding no value, potentially adding negative value since it encourages catching too many exceptions.
Instead, make throws clause contain specific Exceptions, or better yet remove it altogether and use unchecked exceptions.
Thanks for the post.
ReplyDeleteTop Advanced Excel Classes in Bangalore
Your posts are great and teach me a lot. Thanks. Insulation Contractor Services
ReplyDelete