重写的方法无法引发Java异常 [英] Overridden methods cannot throw exceptions Java

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

问题描述

这是我的代码块.

class Alpha{
    public void Gamma() {
        System.out.println("Alphas");
    }
}

class Beta extends Alpha{
    public void Gamma() throws Exception //Line 1
    {
        try {
            System.out.println("Betas");
        } catch(Exception e) {
            System.out.println("Exception caught");
        } finally {
            System.out.println("xfg");
        }
    }
    public static void main(String[] args) throws Exception {
        Alpha g = new Beta();
        g.Gamma();
    }
}

此代码无法编译,因为我在Line1中添加了"throws".

This code fails to compile because I have added "throws" in Line1.

编译器抱怨重写的方法无法引发异常.

The compiler complains that overridden methods cannot throw exceptions.

为什么呢?.

为什么覆盖的方法不能引发异常?.

Why cant an overridden method throw an exception ?.

因为我可以通过在子类的实现中添加n行代码来覆盖基类中的方法.

Because I can override a method from a base class by adding n lines of code in the child's class implementation.

这些添加的代码会引发异常,所以为什么不能在重写的方法中使用"throws"?.

And these added code can throw an exception so why I cant use "throws" in the overridden method ?.

推荐答案

被重写的方法可以抛出异常,只要被重写的方法也抛出相同的异常.您不能引入新异常.

Overridden methods can throw Exceptions, so long as the method being overridden also throws the same Exceptions. You can't introduce new Exceptions.

那么为什么不能引入新的例外?

So why can't you introduce a new Exception?

OOP的中心概念之一是使用抽象类型,并且所有子类型都可以视为抽象类型.请参见李斯科夫替代原则

One of the central concepts of OOP is using abstract types, and that all subtypes may be treated as the abstract type. See Liskov Substitution Principle

之所以不能引入更广泛的行为,是因为如果抽象类型(超类或接口)中的方法没有引发异常,并且您将对象引用为该类型,则可能会出现意外的行为:

The reason you can't introduce broader behaviour is that if the method from the abstract type (super class or interface) doesn't throw an Exception and you refer to your object as that type, you'd get unexpected behaviour:

Alpha alpha = new Beta();
// At this point, the compiler knows only that we have an Alpha
alpha.myMethod();

如果Alpha的myMethod()没有引发异常,而Beta的发生了,则在上面的代码中我们可能会得到意外的异常.

If Alpha's myMethod() doesn't throw an Exception, but Beta's does, we could get an unexpected Exception in the above code.

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

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