exception - 指导异常处理政策的原则是什么?

标签 exception error-handling

处理异常涉及很多相关性。除了低级 API(异常涵盖硬件和操作系统引发的错误)之外,还有一个阴暗区域,程序员可以在其中决定什么构成异常,以及什么是正常情况。

您如何决定何时使用异常? 您对于异常(exception)情况有一致的政策吗?

最佳答案

异常不应该用作在对象内部的方法之间传递信息的方法,在本地您应该使用错误代码和防御性编程。

异常旨在将控制从检测到错误的点传递到可以处理错误的位置(堆栈的较高层),大概是因为本地代码没有足够的上下文来纠正问题和更高级别的内容堆栈向上将有更多上下文,从而能够更好地组织恢复。

在考虑异常时(至少在 C++ 中),您应该考虑 API 所做的异常保证。最低保证级别应为基本保证,但您应努力(在适当情况下)提供强有力的保证。如果您不使用特定 API 的外部依赖项,您甚至可以尝试提供不抛出保证。

注意:不要将异常保证与异常规范混淆。

异常(exception)保证:

无保证:

There is no guarantee about the state of the object after an exception escapes a method In these situations the object should no longer be used.

基本保证:

In nearly all situations this should be the minimum guarantee a method provides. This guarantees the object's state is well defined and can still be consistently used.

强有力的保证:(又名交易保证)

This guarantees that the method will completely successfully Or an Exception will be thrown and the objects state will not change.

无抛出保证:

The method guarantees that no exceptions are allowed to propagate out of the method. All destructors should make this guarantee.
| N.B. If an exception escapes a destructor while an exception is already propagating
| the application will terminate

关于exception - 指导异常处理政策的原则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/106586/

相关文章:

java - 如何将 java 循环与 SQL 条件选择混合

从编译的 jar 运行时出现 javafx.fxml.LoadException

c++ - 捕获异常而不必抛出

php - 实时网站错误管理的最佳实践

node.js - Node.js 终端中漂亮的异常消息

ruby-on-rails - AbstractController::DoubleRenderError cannot be fixed with “redirect_to and return”

java - 异常:查询结果集不可修改

javascript - 最终 block 中的return语句

asp.net - 如何覆盖错误页面的页面渲染?

asp.net - httpErrors 在本地计算机上显示 500 错误而不是 YSOD