2

我们在我们的第 4 个也是最后一个 C++ 课程中,我一直在查看 Herb Sutter 关于异常规范的帖子和一些关于 stackoverflow 的帖子,表明异常规范将在下一个 C++ 版本中被弃用。

我可以找到如何实现异常规范的示例,但是在理解异常规范是什么以及它们与异常处理有何不同时,我遇到了一些问题。

在提供一些见解方面的任何帮助都将是最有帮助的。

4

3 回答 3

4

异常规范要求编译器通过调用std::unexpected()或替换集来处理所有未列出的异常类型std::set_unexpected()

它们被普遍认为是一件坏事。

常见的误解:

  • “编译器会检查你是否做了任何可能引发其他异常的事情。” 错误的。在编译时不检查 C++ 异常。编译器不会检查您是否抛出其他类型,也不会检查您是否忘记处理未列出的异常类型。
  • “你不能抛出其他类型的异常。” False,在函数内可以抛出任何异常。在运行时,如果函数将通过任何未列出的异常类型异常终止,则会调用意外处理程序,它有机会将异常替换为列出的类型。

另请参阅std::bad_exception

于 2013-07-16T17:09:53.023 回答
4

异常规范指定函数可能抛出的异常。

于 2013-07-16T17:07:02.153 回答
0

Exceptions specifications, as the name imply, are about specifying which exceptions a function may throw; in general. How the may is enforced however depends on the language.

  • in Java the compiler statically enforces this and will reject the program if ever your function may throw something else (unless the something else derives from a specific base exception class)
  • in C++, the compiler allows the program, however it inserts a runtime check and if ever anything is thrown that was not specified it calls std::unexpected

In general, exceptions specifications are pretty much universally decried because:

  • they do not compose well. If you call two functions throwing each a set X and Y of exceptions, then the resulting function should at least declare the union of X and Y. Since it soon becomes unmanageable you then need to "translate" the exceptions into some common type, wrapping over the original to keep the context. It is not unusual to end up with a 3 or 5 deep exceptions chain.
  • some basic operations may throw. In C++, memory allocation may throw std::bad_alloc; pretty much every single STL collection is thus susceptible for example.

If possible, forget you ever learned about exception specifications.

于 2013-07-16T17:48:16.557 回答