简体   繁体   English

调用带有检查异常的方法

[英]call method with checked exception

As I know if method throws an exception Java compiler forces the caller of that method to catch that exception.据我所知,如果方法抛出异常 Java 编译器会强制该方法的调用者捕获该异常。

I see that parseInt throws NumberFormatException :我看到parseInt抛出NumberFormatException

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

So why I can call it wthout catching the exception:那么为什么我可以在不捕获异常的情况下调用它:

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

Because NumberFormatException extends RuntimeException - Runtime Exceptions are considered to be 'unchecked', See the Javadoc of RuntimeException :因为NumberFormatException扩展了RuntimeException - 运行时异常被认为是“未检查的”,请参阅RuntimeExceptionJavadoc

RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. RuntimeException 是在 Java 虚拟机正常运行期间可以抛出的那些异常的超类。

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.方法不需要在其 throws 子句中声明任何可能在方法执行期间抛出但未被捕获的 RuntimeException 子类。

Here is an article from the Java tutorial explaining how this feature is meant and why it exists这是Java 教程中的一篇文章,解释了此功能的含义及其存在的原因

The important distinction is that any Exception that extends from Runtime exception does not need to be caught, while any other Exception does.重要的区别是任何从运行时异常扩展的异常都不需要被捕获,而任何其他异常都需要。 Exceptions that extend RuntimeException can be thrown at any time, such as NullPointerException or ConcurrentModificationException, and so they can't expect you to try to catch them all.任何时候都可能抛出扩展 RuntimeException 的异常,比如 NullPointerException 或 ConcurrentModificationException,所以它们不能指望你去尝试捕获它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM