gpt4 book ai didi

java - 对抛出异常的困惑

转载 作者:行者123 更新时间:2023-11-29 07:56:22 25 4
gpt4 key购买 nike

好吧,我可能听起来很天真。请原谅我。但我无法理解一个简单的场景。

下面是一段代码

class Utils {
int getInt(String x) throws Exception {
return 7;
}
}

public class Tutorial4 extends Utils {
public static void main(String[] args) {
Utils u = new Tutorial4();
u.getInt("2");

}

int getInt(String arg) {
return Integer.parseInt(arg);
}
}

但是下面的代码显示编译时错误在

u.getInt("2");

它要求我声明或处理异常。

然而,当我重写上述方法时,为什么会显示错误

其次,当我用 NUllPointerException 代替 Exception 时,它没有给我任何错误

背后的概念是什么?

谢谢

最佳答案

It asks me to declare or handle the exception.

没错。当您调用已声明要抛出异常的方法时,调用方法也应声明要抛出该异常,或处理该异常。

However when I am overridding the above method then why it is showing the error

您不能在覆盖方法时移除或减少限制。您的重写方法必须至少声明异常或其在重写方法中声明的子类。

secondly when i give NUllPointerException in place of Exception it gives me no error

NPE 是一个未经检查的异常,因此不需要声明它被抛出。

关于java - 对抛出异常的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17443667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com