Skip to main content

Posts

Showing posts from January, 2017

Java: throws Exception

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 th…