我正在通读一本 Java 教科书中有关异常和断言的一章,并遇到了我有疑问的这段代码。
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();
}
}
在下一段中,文本说“searchFor
方法声明它抛出 StreamException
,以便在清理后将生成的任何异常传递给调用代码,包括调用关闭时抛出的任何 StreamException
。
我的印象是,包含一个 throws
子句允许程序员抛出异常的特定类(或子类),并且当且仅当它抛出一个类或其父类(super class)之一在 throws
子句中。但是这里,在 try
block 中有一个 throws
子句,没有 throw
语句。那么首先包含该子句的意义何在? StreamException
会在代码的什么地方被捕获?
最佳答案
And where in the code would a
StreamException
be caught?
try
有一个finally
但没有catch
。 finally
将执行,Exception
将传播到caller。
关于java - 没有任何 catch 语句的 Try block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33963680/