【问题标题】:nested exceptions and primitive types嵌套异常和原始类型
【发布时间】:2014-02-26 04:22:17
【问题描述】:

当我捕获的异常是原始类型时,我可以使用std::throw_with_nested 吗?

据说,新类型是从捕获的异常和新的异常中衍生出来的。但我不能从像int 这样的原始类型派生。因此我不能使用原始类型的嵌套异常。这是真的吗?

【问题讨论】:

    标签: c++ c++11


    【解决方案1】:

    我的标准副本是这样写的:

    18.8.6/7 抛出:如果U 是非从nested_exception 派生的非联合类类型,则公开的未指定类型的异常从U 和nested_exception 派生并从std::forward<T>(t) 构造,否则std::forward<T>(t)。

    所以throw_with_nested(42) 应该throw 42;

    【讨论】:

      【解决方案2】:

      标准说throw_with_nested(T && t),U = remove_reference<T>::type:

      抛出:如果U 是非联合类类型,它不是从nested_exception 派生的,则从U 和nested_exception 公开派生并构造的未指定类型的异常来自std::forward<T>(t),否则来自std::forward<T>(t)。

      “否则”子句似乎是说,如果您没有类类型,则只需抛出原始参数。

      【讨论】:

        【解决方案3】:

        抛出的异常是从 new 异常和std::nested_exception(不是新的和捕获的)派生的未指定类型。然后std::nested_exception 包含一个std::exception_ptr 到捕获的异常(从std::current_exception 获得)。

        所以:

        如果 new 异常是 int,那么您将抛出 int,正如其他答案所述。

        如果你捕获一个int,那么你在std::nested_exception 中抛出(一个派生的类型)带有int 的新异常。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-02-18
          • 1970-01-01
          • 1970-01-01
          • 2023-03-25
          • 2014-06-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多