gpt4 book ai didi

java - 带有已检查异常的调用方法

转载 作者:行者123 更新时间:2023-12-02 06:06:57 25 4
gpt4 key购买 nike

据我所知,如果方法抛出异常,Java 编译器会强制该方法的调用者捕获该异常。

我看到 parseInt 抛出 NumberFormatException :

public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);

那么为什么我可以调用它而不捕获异常:

String str = "5";
int n = Integer.parseInt(str);

最佳答案

因为 NumberFormatException 扩展了 RuntimeException - 运行时异常被视为“未检查”,请参阅 Javadoc RuntimeException:

RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.

A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.

这里是an article from the Java tutorial解释此功能的含义以及它存在的原因

关于java - 带有已检查异常的调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6133852/

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