Java中未检查的异常:继承自Error或RuntimeException? [英] Unchecked exceptions in Java: Inherit from Error or RuntimeException?
问题描述
我想使用(未选中)异常来处理错误。我听说,对于每种异常,我应该创建一个Error或RuntimeException的子类。
有什么区别?
I would like to handle errors with (unchecked) exceptions. I heared that for each kind of exception I should create a subclass of either Error or RuntimeException. What's the difference?
推荐答案
错误
应该以编程方式识别出不可恢复的问题(例如内存不足)。 例外
应该以编程方式识别由于代码外的意外状况(例如数据库关闭)引起的可恢复问题。 RuntimeExceptions
应该以编程方式识别由代码流中的错误引起的可恢复的问题(读取:开发人员的错误,如空指针,非法参数等)。
Errors
should identify programmatically unrecoverable problems (e.g. out of memory). Exceptions
should identify programmatically recoverable problems which are caused by unexpected conditions outside control of code (e.g. database down). RuntimeExceptions
should identify programmatically recoverable problems which are caused by faults in code flow (read: developer's faults such as null pointer, illegal argument, etc).
你想从 RuntimeException
继承你的案例。
这篇关于Java中未检查的异常:继承自Error或RuntimeException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!