0

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?

glyphx
  • 195
  • 3
  • 10
  • You should show us the relevant code – chancea Jul 29 '13 at 21:57
  • 1
    No. You should never `throws Throwable`. You should throw a useful and indicative exception. – Boris the Spider Jul 29 '13 at 21:57
  • 1
    @BoristheSpider I completely agree, but if he inherited this code and changing that breaks something then possible showing us the code could help us understand if he is able to change it – chancea Jul 29 '13 at 21:59
  • 1
    I've also seen this in code that I inherited, so some book / article somewhere must say to do this, but it's not a good idea. Likely the cause of your Eclipse error is that you're overriding a method that throws `Throwable` with a method that you've modified to only throw the relevant exceptions, or you're calling a method that throws `Throwable` from a method that you've modified to only throw the relevant excpetions - if you're not able to edit the problematic methods (e.g. if they're in a jar) then you're probably stuck with throwing `Throwable`, but there are worse sins to commit – Zim-Zam O'Pootertoot Jul 29 '13 at 22:03
  • Can you please provide a code example that illustrates the compiler error that you are trying to solve? – Code-Apprentice Jul 29 '13 at 22:16

1 Answers1

5

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."

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151