gpt4 book ai didi

java - 在 ByteArrayInputStream 的 read 方法中抛出异常

转载 作者:行者123 更新时间:2023-12-02 05:04:36 24 4
gpt4 key购买 nike

当我阅读ByteArrayInputStream源代码时,我看到方法read不会抛出IOException,尽管有throws InputStream 类的 read 方法声明。

之前,我在重写方法时保持方法签名相同。因此,如果一个方法声明了 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.

因此,如果以下内容是基类的一部分:

public int read() throws IOException;

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

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,因为它根本不可能发生。此处不会发生针对可能抛出 IOException 的资源的 I/O,当读取所有字节时,仅返回 -1。因此签名不同。

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

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

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

关于java - 在 ByteArrayInputStream 的 read 方法中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27902554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com