Closeable 接口的 close() 方法在签名中是否有异常

Does close() method of the Closeable interface has exception in the signature

我是第一次阅读 Closeable 和 AutoCloseable 接口。 根据我的理解,除了来自 Closeable 接口的 close 方法的 IOException 之外,我们不能抛出任何异常,我们可以抛出任何可能的异常,如 IllegalStateException 仅抛出 AutoCloseable 接口。 但是我们可以说Closeable方法的close()方法在签名中有异常吗?

AutoCloseable interface定义close方法如下:

void close() throws Exception

而扩展 AutoCloseableCloseable interface 中的 close 定义如下:

void close() throws IOException

因此,在后一种情况下,您只能抛出 IOException 或从它扩展的任何异常。

请注意,您始终可以抛出任何(未经检查的)运行时异常,例如 IllegalStateException,与方法签名中定义的异常无关。

您是想询问 Closable.close() 方法签名中是否有异常吗?

是的,您可以在此处查看文档:Closeable.close()。它抛出 IOException.

void close() throws Exception 

根据文档,Closeable 扩展了 AutoCloseable。我们将它专门用于 IO 流。因此它抛出 IOException 而不是 Exception.

来自 AutoCloseable.close():

While this interface method is declared to throw Exception, implementers are strongly encouraged to declare concrete implementations of the close method to throw more specific exceptions, or to throw no exception at all if the close operation cannot fail.