Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try block without any catch statements

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?

like image 480
UnworthyToast Avatar asked Nov 27 '15 19:11

UnworthyToast


Video Answer


1 Answers

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.

like image 108
Elliott Frisch Avatar answered Sep 19 '22 00:09

Elliott Frisch