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

标签 java exception runtimeexception

据我所知,如果方法抛出异常,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/

相关文章:

java - 内置逻辑的返回语句

java - ExceptionMapper 的 Jersey/Jackson 异常问题

Clojure REPL 无法解析符号

java - 单行 Lambda 和运行时异常 - 未编译?

java - JFreeChart刷新后恢复缩放位置

java - 如何将此 ArrayListClass 转换为抽象类

javax.inject.Provider 与 String

java - 正则表达式有异常(exception)

c# - 尝试修改字典时出现异常

android - 从 XML 布局扩展 ViewPager