本文介绍了异常和错误之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试更多地了解基本Java和不同类型的Throwables,有人能告诉我异常和错误之间的区别吗?
I'm trying to learn more about basic Java and the different types of Throwables, can someone let me know the differences between Exceptions and Errors?
推荐答案
不应该捕获或处理错误(除了最罕见的情况)。例外是异常处理的基础。 解释得很好:
Errors should not be caught or handled (except in the rarest of cases). Exceptions are the bread and butter of exception handling. The Javadoc explains it well:
查看的一些子类错误
,接受他们的一些JavaDoc评论:
Look at a few of the subclasses of Error
, taking some of their JavaDoc comments:
-
AnnotationFormatError
- 当注释解析器尝试从类文件中读取注释并确定注释格式错误时抛出。 -
AssertionError
- 抛出表示断言已失败。 -
LinkageError
- LinkageError的子类表示某个类对另一个类有一定的依赖性;然而,后一类在前一类的编译后发生了不相同的变化。 -
VirtualMachineError
- 抛出此异常表示Java虚拟机已损坏或已耗尽其继续运行所需的资源。
AnnotationFormatError
- Thrown when the annotation parser attempts to read an annotation from a class file and determines that the annotation is malformed.AssertionError
- Thrown to indicate that an assertion has failed.LinkageError
- Subclasses of LinkageError indicate that a class has some dependency on another class; however, the latter class has incompatibly changed after the compilation of the former class.VirtualMachineError
- Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.
实际上有三个重要的子类别 Throwable
:
There are really three important subcategories of Throwable
:
-
错误
- 大多数应用程序应该崩溃而不是试图解决问题, - 未经检查的异常(又名
RuntimeException
) - 通常是编程错误,例如NullPointerException
或非法论据。应用程序有时可以处理或从此Throwable
类别中恢复 - 或者至少在Thread的run()
方法中捕获它,记录投诉,然后继续运行。 - 检查异常(又名其他所有内容) - 应用程序应能够捕获并有意义地对其余部分执行某些操作,例如
FileNotFoundException
和TimeoutException
...
Error
- Something severe enough has gone wrong the most applications should crash rather than try to handle the problem,- Unchecked Exception (aka
RuntimeException
) - Very often a programming error such as aNullPointerException
or an illegal argument. Applications can sometimes handle or recover from thisThrowable
category -- or at least catch it at the Thread'srun()
method, log the complaint, and continue running. - Checked Exception (aka Everything else) - Applications are expected to be able to catch and meaningfully do something with the rest, such as
FileNotFoundException
andTimeoutException
...
这篇关于异常和错误之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!