为什么覆盖方法可以抛出任何未经检查的异常?

Why can overriding methods throw any unchecked exception?

为什么重写方法会在 java 中抛出未经检查的异常?

为什么覆盖方法不能抛出比被覆盖方法更广泛的异常?不是我的问题。 我只想知道为什么重写方法可以抛出未经检查的异常而不能抛出已检查的异常。

假设一个基 class 有以下方法:

int foo() throws IOException;

也就是说该方法可以

  • return 一个整数
  • 抛出已检查的 IOException
  • 抛出它想要的任何运行时异常,因为不需要在 throws 子句中声明运行时异常

现在让我们在子class 中覆盖此方法。 subclass 必须遵守基方法的约定,所以可以

  • return 一个整数
  • 抛出已检查的 IOException
  • 抛出它想要的任何运行时异常:这不会违反基本方法的约定。

不过,它不能做的是

  • return使用 double、对象或 int 以外的任何东西,因为这会违反基本方法的约定
  • 抛出另一个检查异常,因为那会违反基本方法的约定

why overriding methods can throw unchecked exception in java ?

Java 中的任何方法都可以抛出未经检查的异常。覆盖方法也是一种方法,因此在涉及未经检查的异常时它获得与其他方法相同的特权。

I just want to know why Overriding methods CAN throw unchecked exception while cannot throw checked exception

你这句话的最后一部分不正确。重写方法可以抛出 both checked 和 unchecked 异常。我相信你想问的问题是

  1. 为什么 CAN'T 覆盖方法抛出检查异常而覆盖方法不抛出检查异常。
  2. 为什么 CAN 覆盖方法抛出未经检查的异常,而覆盖方法却没有。

让我们回答 1)

   class Parent {
      public void doSomething() { }
   }

   class Child extends Parent {
      public void doSomething()throws Exception { }
   }

让我们假设上面的代码是允许的。客户端代码将如下所示:

   Parent p = new Child();
   p.doSomething(); 

如果不限制覆盖方法可以抛出哪些已检查异常,则上述代码不会出现编译错误。编译器不知道 Child 中的 doSomething 实际上可以 throw 检查 ExceptionChilddoSomething 方法的 throw Exception 子句有点毫无意义,因为程序员不需要处理已检查的异常。

让我们回答 2)

Oracle tutorial 有一篇很好的文章,对您的问题很有用:

Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.

Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).

由于程序员没有义务捕获方法抛出的 RuntimeException,因此在覆盖方法的情况下对未检查异常设置与已检查异常相同的限制将毫无意义。