为什么捕获RuntimeException不被认为是一个很好的编程实践? [英] Why is catching a RuntimeException not considered a good programming practice?

查看:621
本文介绍了为什么捕获RuntimeException不被认为是一个很好的编程实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要使用 catch(Throwable exc){} 捕获 RuntimeException 不被认为是一个很好的编程习惯?处理RuntimeExceptions的正确方法是什么?

Why is catching a RuntimeException using catch(Throwable exc) {} not considered a good programming practice? What is the right way to handle RuntimeExceptions?

另外,为什么 catch(Exception exc){} not catch 的RuntimeException

Also, why does catch(Exception exc) {} not catch RuntimeException? How is this behavior implemented?

推荐答案

通常, RuntimeException 表示编程错误(在这种情况下,您无法处理它,因为如果您知道希望可以避免错误)。

Usually, a RuntimeException indicates a programming error (in which case you can't "handle" it, because if you knew to expect it you'd have avoided the error).

捕获任何这些一般例外(包括 Throwable )是一个坏主意,因为这意味着你声称你理解每一种可能出错的情况,尽管如此,你仍然可以继续。有时候,在堆栈的顶层捕获异常(但不是通常 Throwable )。在一个网络服务器中 - 因为通常情况下,单个请求出错,您通常希望保持服务器的状态并响应进一步的请求。我通常不会收到 Throwable ,因为这包括通常用于指示真正灾难性错误的错误子类通常通过终止进程来处理最好的

Catching any of these general exceptions (including Throwable) is a bad idea because it means you're claiming that you understand every situation which can go wrong, and you can continue on despite that. It's sometimes appropriate to catch Exception (but not usually Throwable) at the top level of the stack, e.g. in a web server - because usually whatever's gone wrong with a single request, you normally want to keep the server up and responding to further requests. I don't normally catch Throwable, as that includes Error subclasses which are normally used to indicate truly catastrophic errors which would usually be best "handled" by terminating the process.

从根本上说,当有一个错误时,您需要对继续执行特定任务非常谨慎 - 您需要真正拥有对错误的意思是一个很好的想法,否则你可以对世界的状况进行错误的假设,并使事情变得更糟。在大多数案例(并非全部)中,简单地放弃请求比尝试继续进行,而不管神秘的失败如何。 (它确实非常依赖于上下文 - 例如,您可能不在乎当尝试获取一个辅助信息时出错了。)

Fundamentally, when there's an error you need to be very cautious about continuing with a particular task - you need to really have a pretty good idea about what the error means, as otherwise you could go ahead with a mistaken assumption about the state of the world, and make things worse. In most cases (not all), simply giving up on a request is better than trying to carry on regardless of a mysterious failure. (It does very much depend on context though - you might not care what went wrong when trying to fetch one piece of secondary information, for example.)

至于捕获异常不捕捉 RuntimeException - 这根本不是真的。关于 RuntimeException 的唯一奇怪的是它(和子类)是未检查的异常,而异常和所有其他子类异常被检查。

As for catching Exception not catching RuntimeException - that's simply not true. The only odd thing about RuntimeException is that it (and subclasses) are unchecked exceptions, whereas Exception and all other subclasses of Exception are checked.

这篇关于为什么捕获RuntimeException不被认为是一个很好的编程实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆