我有一个类在重写方法中抛出更高的检查异常。我知道这是不允许的,但为什么这段代码有效?
package personaltestlevel1;
public class OverrideExcept {
public static void main(String args[]) {
S1 s = new S2();
try
{
s.show();
}catch (NullPointerException e){
System.out.printf(e.getMessage());
}
}
}
class S1{
public void show() throws NullPointerException {
try
{
System.out.println("not overriden");
}catch (Exception e){
throw new NullPointerException();
}
}
}
class S2 extends S1{
public void show() throws RuntimeException {
try
{
System.err.println("overriden");
}catch (Exception e){
throw new RuntimeException();}
}
}
我已经用检查的异常更新了我的样本 - 它无论如何都可以工作。