I was reading through a Java textbook in a chapter on exceptions and assertions, and came across this block of code that I had a question on.
public boolean searchFor(String file, String word)
throws StreamException
{
Stream input = null;
try {
input = new Stream(file);
while (!input.eof())
if (input.next().equals(word))
return true;
return false; //not found
} finally {
if (input != null)
input.close();
}
}
In the next paragraph, the text says that "the searchFor
method declares that it throws StreamException
so that any exceptions generated are passed through to the invoking code after cleanup, including any StreamException
thrown by the invocation of close.
I was under the impression that including a throws
clause was what allowed a programmer to throw a specific class (or subclass) of an exception, and that a class could be thrown if and only if it or one of its superclasses was in the throws
clause. But here, there is a throws
clause with no throw
statement in the try
block. So what is the point of including the clause in the first place? And where in the code would a StreamException
be caught?
And where in the code would a
StreamException
be caught?
The try
has a finally
but no catch
. The finally
would execute, and the Exception
would propagate to the caller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With