Frage

I am editing someone elses code, and a method had "Throws Throwable". I took that off so eclipse would let me add just the exception types that it needs to throw... however I have an error on a method called to the super class (which I have no access currently) that says "Unhandled exception type Throwable".

Based on what I know and based on what I have seen in this cods my guess is that this is something that just should not be done... but can someone confirm?

War es hilfreich?

Lösung

It is sometimes reasonable for a method to declare that a method throws Exception. Usually, more specific exceptions are desirable.

For example, the Callable interface has a method that throws Exception:

public interface Callable<V> {
    V call() throws Exception;
}

A Throwable could be either an Exception or an Error. An Error indicates an exception that an application should not try to catch. Any method can throw it, and there's no need to declare it.

From Joshua Bloch's "Effective Java", 2nd ed:

"Always declare checked exceptions individually, and document precisely the conditions under which each is thrown using the Javadoc @throws tag. Don't take the shortcut of declaring that a method throws some superclass of multiple exception classes it can throw. As an extreme example, never declare that a method "throws Exception" or, worse yet, "throws Throwable."

This is almost always the best guideline, with a few exceptions to Bloch's absolute prohibition against "throws Exception."

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top