为什么Java中存在已检查和未检查的异常 [英] Why there is checked and unchecked exception in Java
问题描述
可能重复:
Java:checked vs unchecked exception explanation
为什么要检查和取消选中例外?
为什么Java中的两个异常类型名为checked和unchecked?选择此类异常的原因是什么?
Why is the two exception types in Java named "checked" and "unchecked"? What is the reason behind choosing this type of exceptions ?
推荐答案
检查异常扩展 java.lang.Exception
,而未经检查的异常扩展 java.lang.RuntimeException
,或 java.lang.Error
。
Checked exceptions extend java.lang.Exception
, while unchecked exceptions extend java.lang.RuntimeException
, or java.lang.Error
.
Exception
extends java.lang.Throwable
,同时 RuntimeException
extends Exception
, Error
,如 Exception
,extends java.lang.Throwable
。
Exception
extends java.lang.Throwable
, while RuntimeException
extends Exception
, and Error
, like Exception
, extends java.lang.Throwable
.
在决定是否您应该使用已检查与未检查的异常,请始终记住以下规则:
When deciding whether you should be using a checked vs. unchecked exception, always remember these rules:
-
异常
S是应用程序想要处理的情况。 -
RuntimeException
S是您(通常)无法处理的情况编程错误。您不应该捕获RuntimeException
S,它们应该在您的单元测试中定位,并在您的生产代码中修复。 -
错误
S是由于严重错误而无法处理的情况,例如系统问题(例如文件系统失败)。你不应该抛出,捕获或子类化错误
,除非你正在为JVM构建一些编译器。
Exception
S are cases an application would want to handle.RuntimeException
S are cases you (usually) can't handle, due to programming error. You shouldn't catchRuntimeException
S, they should be targeted in your unit testing, and fixed in your production code.Error
S are cases you can't handle because of critical errors, such as system problems (e.g. file system has failed). You shouldn't ever throw, catch or subclass anError
, unless you're building something such as a compiler for the JVM.
这篇关于为什么Java中存在已检查和未检查的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!