覆盖方法与异常 [英] Overriding Method with Exception

查看:134
本文介绍了覆盖方法与异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这里是这本书的引用:

So here is the quote from the book:


重写方法不能抛出新的或更广泛的被检查的异常通过重写方法。例如,声明FileNotFoundException的方法不能被声明SQLException,异常或任何其他非运行时异常的方法覆盖,除非它是FileNotFoundException的子类。

The overriding method must NOT throw checked exceptions that are new or broader than those declared by the overridden method. For example, a method that declares a FileNotFoundException cannot be overridden by a method that declares a SQLException, Exception, or any other non-runtime exception unless it's a subclass of FileNotFoundException.

现在这里是我的问题,如果超类中的方法引发异常,那么覆盖方法是否可以抛出异常呢?

Now here is my question, if the method in the superclass throws an exception, then can the overriding method NOT throw an exception at all?

因为我刚刚在Java中尝试过这个,覆盖方法没有抛出任何异常,没有错误。

Because I just tried this in Java, where the overriding method did not throw any exceptions, and there was no error.

请解释。

推荐答案

您可以声明一个重写方法,因为抛出的异常类型超过超类,您只能不能引入新的异常。子类方法必须与超类方法的行为兼容。更确切地说,您必须能够将子类的对象替换为超类的对象,而不会破坏任何东西(在throws子句中添加新的检查异常将意味着调用它的代码将不得不更改其代码来处理它)。

You can declare an overriding method as throwing less types of exceptions than the superclass, you just can't introduce new ones. The subclass method has to be compatible with the behavior of the superclass method. More exactly, you have to be able to substitute objects of the subclass for objects of the superclass without breaking anything (where adding a new checked exception to the throws clause would mean things calling it would have to change their code to handle it).

(背后的想法是 Liskov替代原则:程序应该能够处理高级对象,而不会陷入关于所有确切类型的细节。如果子类可以引入更改,这意味着程序必须选择它们并且处理它们不同,那么它会违背抽象的目的。 )

(The idea behind this is the Liskov Substitution Principle: a program should be able to deal with objects at a high level without getting bogged down in details about everything's exact type. If subclasses can introduce changes that mean the program has to pick them out and handle them differently then it defeats the purpose of abstraction.)

所以一个重写的方法可以被声明为抛出没有检查的异常(完全省略throws子句),因为这不需要更改任何调用者。

So an overriding method can be declared as throwing no checked exceptions at all (by omitting the throws clause entirely), because that doesn't require changes to any callers.

JDK中有例子,例如java.io中的子类不能抛出超类声明的异常(请参阅 ByteArrayOutputStream close方法)。这里的close方法可能会删除其throws子句,因为它不会抛出IOException。 (也许这是一个机会,有人想要使用抛出IOException的版本进行子类化?)

There are examples in the JDK, such as in java.io, where the subclass can't possibly throw an exception declared by the super class (see the ByteArrayOutputStream close method). Here the close method could have had its throws clause removed, since it never throws IOException. (Maybe it was left on the chance someone would want to subclass it with a version that did throw IOException?)

这篇关于覆盖方法与异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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