在 ByteArrayInputStream 的读取方法中抛出异常

throwing exception in read method in ByteArrayInputStream

当我阅读 ByteArrayInputStream 资源时,我看到方法 read 不会抛出 IOException 尽管 read 方法声明中有 throws InputStream class。

之前我在覆盖方法时保持方法签名相同。因此,如果一个方法声明了 throws - 我实现了它。

但现在我很好奇 - 为什么 ByteArrayInputStream 中的方法 read 不会抛出 IOException(这样的错误永远不会发生?)以及为什么这样的行为(我的意思是没有 throws IOException声明)是否允许?

嗯,基本上你只能减少或消除在你重写的方法中抛出的异常。不允许抛出更广泛的异常。

来自JLS

The throws clause of an overriding method may not specify that this method will result in throwing any checked exception which the overridden method is not permitted, by its throws clause, to throw.

所以,如果下面是基础的一部分class:

public int read() throws IOException;

然后,以下规则适用于子classes:

public int read(); // OK, not broader (but more narrow)

public int read() throws SubClassOfIOException; // Ok, it is not broader (but more narrow)

public int read() throws Exception; // NOT OK, this is broader since Exception is broader than IOException

ByteArrayInputStream 的情况下,没有理由抛出 IOException,因为它根本不可能发生。没有 I/O 针对可以抛出 IOException 的资源发生在这里,当读取所有字节时 -1 只是返回。因此签名不同。

但是,当您使用以下内容时:

InputStream stream = new ByteArrayInputStream("text".getBytes());
stream.read(); // Must be caught

这里,被引用的对象被认为是一个InputStream。因此 read 方法仍然被声明为抛出一个 IOException.

它不会抛出异常,因为它是以 return -1 值的方式实现的。值 byte 被 returned 作为 0 到 255 范围内的 int。如果因为已到达流的末尾而没有可用字节,则值 -1 被 returned。一个字节一个字节地读取数据直到达到-1就足够了-就是这样。