重写的方法不能抛出异常 Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18426076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Overridden methods cannot throw exceptions Java
提问by UnderDog
This is my code block.
这是我的代码块。
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();
}
}
This code fails to compile because I have added "throws" in Line1.
此代码无法编译,因为我在 Line1 中添加了“throws”。
The compiler complains that overridden methods cannot throw exceptions.
编译器抱怨被覆盖的方法不能抛出异常。
Why so ?.
为什么这样 ?。
Why cant an overridden method throw an exception ?.
为什么被覆盖的方法不能抛出异常?。
Because I can override a method from a base class by adding n lines of code in the child's class implementation.
因为我可以通过在子类实现中添加 n 行代码来覆盖基类中的方法。
And these added code can throw an exception so why I cant use "throws" in the overridden method ?.
这些添加的代码可以抛出异常,所以为什么我不能在重写的方法中使用“抛出”?。
采纳答案by Bohemian
Overridden methods can throw Exceptions, so long as the method being overridden also throws the same Exceptions. You can't introducenew Exceptions.
被重写的方法可以抛出异常,只要被重写的方法也抛出相同的异常。你不能引入新的异常。
So why can't you introduce a new Exception?
那么为什么不能引入一个新的 Exception 呢?
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
OOP 的核心概念之一是使用抽象类型,并且所有子类型都可以被视为抽象类型。参见Liskov 替换原则
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();
If Alpha's myMethod()
doesn't throw an Exception, but Beta's does, we could get an unexpected Exception in the above code.
如果阿尔法的myMethod()
不抛出一个异常,但测试版的呢,我们可以得到在上面的代码意外的异常。
回答by Juned Ahsan
The rule says
规则说
"Subclass overridden method cannot throw more exceptions than that of super class method".
“子类重写方法不能抛出比超类方法更多的异常”。
回答by Mik378
Your client side always think to deal with the base version. That's the whole benefit of polymorphism => client side ignores the overriden one.
您的客户端总是想处理基本版本。这就是多态的全部好处 => 客户端忽略覆盖的。
Thus, nothing will force the client to deal with specific rules made by the overriden, here the case of a potential exception thrown by the overidden method.
因此,没有什么会强制客户端处理由覆盖的特定规则,这里是覆盖方法抛出的潜在异常的情况。
That's why an overriden method can't throw broader exceptions. It would break the contract.
这就是为什么被覆盖的方法不能抛出更广泛的异常。它会破坏合同。
Thus, regarding this logic, rule is: Overriden method CAN (if it want) only throw a subpart of the exceptions declared in the base version BUT CANNOT throw broader ones.
因此,关于此逻辑,规则是: 覆盖方法 CAN(如果需要)仅抛出基本版本中声明的异常的子部分,但不能抛出更广泛的异常。
回答by user207421
The compiler complains that overridden methods cannot throw exceptions
编译器抱怨被覆盖的方法不能抛出异常
No it doesn't. Read the message again. It says you can't throw an exception that isn't declared to be thrown by the overridden method. Not the same thing at all.
不,它没有。再次阅读邮件。它说您不能抛出未声明为由重写方法抛出的异常。根本不是一回事。
回答by vikas singh
your above code in main method
您在 main 方法中的上述代码
Alpha g = new Beta(); // now it's create a new actual object of Betaclass with refrence of Alpha
Alpha g = new Beta(); // 现在它创建一个新的Beta类实际对象,参考Alpha
g.Gamma(); // * now compiler look only Gamma() method presents in Alpha class off cource it present in Beta class also by default through inheritance.but compiler looked only at class Alpha and ask a question is contains a method Gamma() and found a answer yes it has.
g.Gamma(); // * 现在编译器只查看 Gamma() 方法出现在 Alpha 类中,默认情况下它也通过继承出现在 Beta 类中。是的。
suppose a condition when java compiler gives facility to throws more checked exceptions in gamma() method in Beta Classthen what will happen
假设一个条件,当 Java 编译器提供了在Beta 类的gamma() 方法中抛出更多已检查异常的便利,那么会发生什么
now at compile time compiler only depend on Gamma() method of class Alpha.it does not force to handle this exception or throws this exception which is wrong because it might throw(supposing to java compiler allow throwing more checked exception in overridden method). but in reality compiler not make restriction on throwing exceptions but also on accessibility modifier.
because non static method invocation happen on actual object method not on type and we give to any super type and at compilation time compiler only check accessibility and presence in that type of assigned class.
现在在编译时编译器只依赖于 Alpha 类的 Gamma() 方法。它不会强制处理这个异常或抛出这个错误的异常,因为它可能会抛出(假设 Java 编译器允许在重写的方法中抛出更多的检查异常)。但实际上编译器不限制抛出异常,但也限制可访问性修饰符。
因为非静态方法调用发生在实际对象方法上而不是类型上,我们赋予任何超类型,并且在编译时编译器只检查该类型分配的类中的可访问性和存在性。
so i think that's the reason behind this overridden contract
所以我认为这就是这个被覆盖的合同背后的原因
? The method definition cannot narrow the accessibility of the method, but it can widen it. ? The method definition can only throw all or none, or a subset of the checked exceptions (including their subclasses) that are specified in the throws clause of the overridden method in the superclass.
? 方法定义不能缩小方法的可访问性,但可以扩大它。? 方法定义只能抛出所有或不抛出,或在超类中重写方法的 throws 子句中指定的已检查异常的子集(包括它们的子类)。
回答by PVH
Subclass overriden method/methods can throw (Declare) only unchecked exceptionlike ArrayIndexOutOfBoundsException.
子类覆盖的方法/方法只能抛出(声明)未经检查的异常,如 ArrayIndexOutOfBoundsException。
But you can't throws (declare) the checked exception. like IOException.
但是您不能抛出(声明)已检查的异常。像IOException。
example to overridden methods throw exceptions Java
重写方法抛出异常 Java 的示例
class A{
public void show(){
// some code here
}
}
class B extends A{
public void show() throws ArrayIndexOutOfBoundsException{
// some code here
}
}
Hope these may help you.
希望这些可以帮到你。