异常与 throws 子句不兼容的原因是什么? [英] What are reasons for Exceptions not to be compatible with throws clauses?

查看:31
本文介绍了异常与 throws 子句不兼容的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我异常可能有什么原因,与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{

    }
}

Exception Exception 与 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 的子类).基类/接口的客户端希望其实例遵守基方法声明的契约,因此从该方法的实现中抛出 Exception 会破坏契约(并且 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆