当我阅读ByteArrayInputStream
来源时,我看到read
方法虽然IOException
throws
方法声明中read
,但InputStream
不会抛出throws
}类。
在重写方法之前保持方法签名相同之前。因此,如果方法已声明read
- 我实现了它。
但现在我很好奇 - 为什么ByteArrayInputStream
中的方法IOException
不会抛出throws IOException
(这种错误永远不会发生?)以及为什么会出现这种行为(我的意思是没有{{1}}允许声明?
答案 0 :(得分:2)
好吧,基本上你只能减少或消除被覆盖方法中抛出的异常。不允许抛出更广泛的例外。
来自JLS:
重写方法的throws子句可能没有指定此方法将导致抛出任何被抛出的方法不允许被抛出的方法抛出的被检查的异常。
因此,如果以下是基类的一部分:
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
时,才会发生针对可以抛出-1
的资源的I / O.因此签名是不同的。
但是,当您使用以下内容时:
InputStream stream = new ByteArrayInputStream("text".getBytes());
stream.read(); // Must be caught
这里,引用的对象被认为是InputStream
。因此,read
- 方法仍然被声明为抛出IOException
。
答案 1 :(得分:0)
它不会抛出异常,因为它以这种方式实现以返回-1值。值字节作为int返回,范围为0到255.如果没有字节可用,因为已到达流的末尾,则返回值-1。只需逐字节读取数据就足够了,直到达到-1 - 这就是全部。