什么是异常的原因不符合throws子句? [英] What are reasons for Exceptions not to be compatible with throws clauses?
问题描述
任何人都可以告诉我异常可能有什么原因,不能与throws子句兼容
Can anyone tell me what reasons exceptions can have, not to be compatible with "throws" clauses
例如:
class Sub extends Super{
@Override
void foo() throws Exception{
}
}
class Super{
void foo() throws IOException{
}
}
异常异常与Super.foo()中的throws子句不兼容
推荐答案
没有完整的代码示例,我只能猜测:你是覆盖/实现一个子类的方法,但异常规范子类方法与超类/接口方法的子类方法不兼容(即不是子集)?
Without a full code sample, I can only guess: you are overriding/implementing a method in a subclass, but the exception specification of the subclass method is not compatible with (i.e. not a subset of) that of the superclass/interface method?
如果基础方法被声明为不抛出异常,则可能会发生这种情况或者例如 java.io.IOException
(它是 java.lang.Exception
的子类,您的方法正在尝试抛出) 。基类/接口的客户端期望其实例遵守基础方法声明的合同,因此从该方法的实现中抛出异常
会破坏合同(和<一个href =http://en.wikipedia.org/wiki/Liskov_substitution_principle =noreferrer> LSP )。
This can happen if the base method is declared to throw no exceptions at all, or e.g. java.io.IOException
(which is a subclass of java.lang.Exception
your method is trying to throw here). Clients of the base class/interface expect its instances to adhere to the contract declared by the base method, so throwing Exception
from an implementation of that method would break the contract (and LSP).
这篇关于什么是异常的原因不符合throws子句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!