本文介绍了在Java中使用带有覆盖方法的throws子句时遇到错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 当我在 demo()方法中使用throw子句时遇到错误,我想知道在继承中使用throws的局限性是什么。 错误是:异常 ClassNotFoundException 与 Test.demo中的throws子句不兼容()。 Class Test { public void demo()引发NumberFormatException,ArrayIndexOutOfBoundsException //错误 { //此处为} public void demo(String s) { //此处为$ b / b} } //测试类的结束 公共类MyTest扩展了测试 { public void demo()抛出IndexOutOfBoundsException,ClassNotFoundException { //此处是} public static void main(String [] args) { } } 解决方案 ClassNotFoundException 是受检查的异常-并且您不能声明方法重写将抛出其覆盖的方法未声明的所有受检查的异常。 摘自第8.4.8.3节JLS : 覆盖或隐藏另一个方法的方法,包括实现接口中定义的抽象方法的方法,可能不会被声明抛出比被覆盖或隐藏的方法更多的检查异常。 考虑一下,例如: Test t = new MyTest(); t.demo(); 该代码中没有任何内容表明 ClassNotFoundException 将被抛出,因为 Test.demo()没有声明将被抛出。但是,检查异常的全部要点是强制调用者 考虑如何处理它们(捕获它们或声明他们也可能抛出异常)。覆盖方法并声明它引发了一个新的检查异常,而原始方法声明未涵盖该异常的能力将使该情况变得毫无意义。 I am getting a error when i am using a throw clause with the method demo().And i want to know that what are the limitations of using throws in inheritance.The error is: Exception ClassNotFoundException is not compatible with throws clause in Test.demo().Class Test{ public void demo() throws NumberFormatException, ArrayIndexOutOfBoundsException//error { //something here } public void demo(String s) { //something here }}//end of Test classpublic class MyTest extends Test{ public void demo() throws IndexOutOfBoundsException,ClassNotFoundException { //something here } public static void main(String[] args) { }} 解决方案 ClassNotFoundException is a checked exception - and you can't declare that a method override will throw any checked exceptions that the method it's overriding doesn't declare.From section 8.4.8.3 of the JLS: A method that overrides or hides another method, including methods that implement abstract methods defined in interfaces, may not be declared to throw more checked exceptions than the overridden or hidden method.Consider, for example:Test t = new MyTest();t.demo();There's nothing in that code to indicate that ClassNotFoundException will be thrown, because Test.demo() doesn't declare that it will be thrown. However, the whole point of checked exceptions is that the caller is forced to consider what to do with them (catch them or declare that they might throw the exception too). The ability to override a method and declare that it throws a new checked exception not covered by the original method declaration would make a nonsense of that. 这篇关于在Java中使用带有覆盖方法的throws子句时遇到错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-23 13:54