-1

When would a situation call for a method to have both throws and throw when the calling method will catch the throws anyway. Take the following method with a custom exception created for my personal program for example.

.....
.....

public String get() throws EmptyQueueException {
 if( planet == mars)
   throw new EmptyQueueException();

 return galaxy;

.....
.....

Sure one declares and one actually pass on the exception but this method is not responsible. I mean if you know this particular exception is going to happen why write it twice considering either will be caught by the invoking method that would have caught it anyway. Why write both throw and throws when one is enough ?

Leosam
  • 33
  • 2
  • 2
    How is one enough? `throws` declares that the method _can_ throw, this is to force a consumer to handle this case. `throw` actually throws the `Exception` - this is an implemetnation detail. Do you suggest that we should review all code in every library to determine what exceptions could be thrown? – Boris the Spider Aug 11 '18 at 16:01
  • 2
    One is not enough. if you write throws without throw, you're lying, since the method doesn't actually throw the exception. And if you write throw without throws, you're lying, because you throw an exception without declaring that this exception can be thrown, without documenting it, and without forcing the caller to catch it, which is the whole point of checked exceptions. – JB Nizet Aug 11 '18 at 16:01
  • Maybe you're suggesting the `throws` should be inferred? – Sotirios Delimanolis Aug 11 '18 at 16:05
  • Lets go to another method for input instead, I declared throws 'java.io.IOException' but I did not throw it. But another method that uses the method still caught it in its own try & catch as its reponsible. – Leosam Aug 11 '18 at 16:13
  • OK and what is your question? The method declares that it **can** throw an IOException, so the caller must catch it. Maybe it doesn't throw one now, but maybe tomorrow it will. Or maybe overriding methods will. the throws clause is part of the **contract** of the method, that it promises to all users of the method not to violate. So it says: beware: this method might throw an IOException, but I promise I will never throw any other checked exception. – JB Nizet Aug 11 '18 at 16:22
  • Alright I think I know what your saying, might have encountered some bad coding practices that confused me. – Leosam Aug 11 '18 at 16:27
  • 1
    .... or a bad tutorial – Hovercraft Full Of Eels Aug 11 '18 at 16:31

1 Answers1

3

Throws on the method declaration, declares a possibility that the method may throw that exception type which as to be caught or managed by any calliing method. Throw actually throws the exception.