在overriden方法中删除throws,编译器在调用时需要try / catch块 [英] Removing throws in overriden method, compiler wants a try/catch block when invoking
问题描述
我有一个子类,我重写了继承的父方法:我从方法声明中删除了throws子句。
I have a subclass and I am overriding the inherited parent method: I am removing the throws clause from the method declaration.
现在,使用多态,我的实例是运行时类型应该确定方法实现;然而,当我尝试编译时,编译器抱怨并想要一个围绕方法调用的try / catch块,就像调用超类方法而不是子类版本一样?
Now, using polymorphism, the my instance's runtime type should determine the method implementation; yet, the compiler complains and wants a try/catch block around the method invocation when I try to compile, as if the superclass method is being invoked and not the subclass version?
我知道我可以删除throws声明或缩小已检查的异常,这可以在覆盖时抛出。为什么这仍然抛出异常?
I'm aware that I can remove the throws declaration or narrow down the checked exception which can be thrown when overriding. Why is this still throwing the exception?
class A{
void foo()throws Exception{throw new Exception();}
}
class SubB extends A{
@Override
void foo(){ System.out.println("B");
}
public static void main(String[] args) {
A a = new SubB();
a.foo(); //compiler reports: unhandled exception type Exception
}
推荐答案
编译器发送 A
,其中 抛出异常。如果您告诉编译器它是一个实际的 SubB
对象,它将停止抱怨
The compiler ses an A
which does throw an Exception. If you however told the compiler it's an actual SubB
object it will stop complaining
SubB b = new SubB();
b.foo();
这篇关于在overriden方法中删除throws,编译器在调用时需要try / catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!