选中的异常将覆盖 java



当我的大师类抛出检查异常时,覆盖方法不应该也实现检查异常吗?

class Master{
    String doFileStuff() throws FileNotFoundException{
        return "a";
    }
}
public class test extends Master{
    public static void main(String[] args){
    }

    String doFileStuff(){
        return "a";
    }
}   

重写方法应保留相同的协定。

基本上,这意味着它可以抛出FileNotFoundExceptionFileNotFoundException子类列表,但并非必须如此。

检查此示例:

Master a = new test();
a.doFileStuff(); //this line might throw an exception, and you should catch it.
                 //but it is not illegal for test class not to throw an exception

现在,我们可以对 FileNotFoundException 的子类做同样的事情,对不同于 FileNotFoundException 的其他例外做同样的事情。对于后面的情况,我们将看到我们的代码甚至不会编译,因为类doFileStuff方法抛出不同的未FileNotFoundException检查异常是非法test

不是真的,只是为了在代码中显示 Allow 评论的原因

当您实际有获取异常的风险时,可能会引发异常,如果您的代码中有某处throw new FileNotFoundException();您被迫添加 try catch 或抛出异常。但是,如果您要覆盖,则可以删除威胁,并且如果添加一些新风险,则必须在新方法中处理它们。

import java.io.FileNotFoundException;
class Master {
  String doFileStuff() throws FileNotFoundException {
    throw new FileNotFoundException(); // it always throws an exception.
  }
}
public class Test extends Master {
  public static void main(String[] args) {
    String a = new Test().doFileStuff();
    String b = new Master().doFileStuff();
  }
  String doFileStuff() {
    return "a"; //It always returns a. No risks here.
  }
}
重写

方法不必重新声明超类方法引发的所有Exception。 只需要它不声明要抛出的Exception不是由超类方法抛出

的。

JLS第8.4.8.3节阐述了:

更准确地说,假设 B 是一个类或接口,而 A 是一个 B 的超类或超接口,以及 B 中的方法声明 n 重写或隐藏 A 中的方法声明 m。然后:

  • 如果 n 有一个 throws 子句,其中提到了任何已检查的异常类型, 然后 m 必须有一个 throws 子句,否则会发生编译时错误。

  • 对于 n 的抛出子句中列出的每个选中的异常类型, 相同的异常类或其超类型之一必须出现在 删除 M 的抛掷条款 (§4.6(;否则,编译时 发生错误。

  • 如果 m 的未擦除抛出子句不包含 n 的 throws 子句中的每个异常类型,一个编译时 出现未经检查的警告。

这是有道理的。 为什么子类方法可能抛出与它覆盖的超类方法相同的Exception? 不声明其他异常是有意义的,因为这会破坏这种情况:

public class Super
{
   public void method() throws FooException {}
}
public class Sub extends Super {
{
   public void method() throws FooException, BarException {}
}

然后用法变得不清楚:

Super sup = new Sub();
try {
   sup.method();
}
// But the subclass could (if it were allowed here)
// throw BarException!
catch (FooException e) {}  

重写方法时,可以声明所有异常、异常子集或不声明超类方法引发的任何异常。还可以声明任何异常,该异常是超类方法声明的异常的子类。

不能引发任何不是由超类方法声明的异常,除非它是超类方法声明的异常的子类。

它在

子类中是可选的,请查看以下链接:

http://www.tutorialspoint.com/java/java_overriding.htm

最新更新