简体   繁体   中英

java.io.Closeable: why throwing RuntimeException in close() works?

I do not know why this codes compiles on Java 7:

class Lamb implements Closeable{
  @Override
  public void close(){
    throw new RuntimeException();   
  } 
}

Method close() from Closeable throws IOException. When overriding a method the "throws" declaration must remain the same or use a subclass. 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! You can't extend the scope, right?

the "throws" declaration must remain the same or use a subclass.

That's not true. What is true is that the throws clause must be the same or more restrictive . More restrictive either means throwing a more restrictive type of Exception (ie a subclass), or not declaring that it can throw the 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(); . Any method can throw a subclass of RuntimeException (aka unchecked exception), no matter what is written after throws .

RuntimeException是否继承自IOException没有任何区别,因为RuntimeException不参与异常检查,正如您在问题中已经承认的那样。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM