[英]java.io.Closeable: why throwing RuntimeException in close() works?
I do not know why this codes compiles on Java 7:我不知道为什么这些代码在 Java 7 上编译:
class Lamb implements Closeable{
@Override
public void close(){
throw new RuntimeException();
}
}
Method close() from Closeable throws IOException. Closeable 中的 close() 方法抛出 IOException。 When overriding a method the "throws" declaration must remain the same or use a subclass.
覆盖方法时,“throws”声明必须保持不变或使用子类。 Now, the RuntimeException is "runtime" so do not need to be declared (I get to this part) BUT it inherits from Exception and not IOException!
现在,RuntimeException 是“运行时”,因此不需要声明(我进入这一部分)但它继承自 Exception 而不是 IOException! You can't extend the scope, right?
你不能扩大范围,对吧?
the "throws" declaration must remain the same or use a subclass.
“throws”声明必须保持不变或使用子类。
That's not true.这不是真的。 What is true is that the
throws
clause must be the same or more restrictive .正确的是
throws
子句必须相同或更严格。 More restrictive either means throwing a more restrictive type of Exception
(ie a subclass), or not declaring that it can throw the exception.更严格的要么意味着抛出更严格的
Exception
类型(即子类),要么不声明它可以抛出异常。 Not being able to throw an exception is more restrictive than being able to.不能抛出异常比能够抛出异常更具限制性。
I should also point out that even though this method does not implicitly have throws IOException
in its throws
clause, even if it did this would not conflict with throw new RuntimeException();
我还应该指出,即使这个方法在它的
throws
子句中没有隐含地throws IOException
,即使它这样做了,也不会与throw new RuntimeException();
发生冲突throw new RuntimeException();
. . Any method can throw a subclass of
RuntimeException
(aka unchecked exception), no matter what is written after throws
.任何方法都可以抛出
RuntimeException
的子类(即未经检查的异常),无论throws
之后写什么。
RuntimeException
是否继承自IOException
没有任何区别,因为RuntimeException
不参与异常检查,正如您在问题中已经承认的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.