首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::rethrow_if_nested

Defined in header <exception>

?

?

template< class E > void rethrow_if_nested( const E& e );

?

(since C++11)

如果E不是多态类类型,或者std::nested_exception是一个不可访问的或模棱两可的基类。E没有效果。

否则,执行。

二次

代码语言:javascript
复制
if (auto p = dynamic_cast<const std::nested_exception*>(std::addressof(e)))
    p->rethrow_nested();

二次

参数

e

-

the exception object to rethrow

返回值

%280%29

可能的实施

命名空间详细信息{模板<class E>结构罐[医]动态[医]演员:STD::[医]常数<bool,std::is[医]多态<E>*价值&%28%21标准::IS[医]底座[医]<std::嵌套[医]异常,E>::valueSTD::是[医]可兑换<E%2A,STD::嵌套[医]例外%2A>::值%29>{};模板<class T>空重抛[医]如果[医]巢式[医]IMPLE%28%T&E,STD::true[医]类型%29{if%28 AUTO NEP=Dynamic[医]CAST<Const STD::嵌套[医]例外%2A>%28std::地址:%28e%29%29%29 nep->重新抛出[医]嵌套%28%29;}模板<class T>空重抛[医]如果[医]巢式[医]IMPL%28 const T&,STD::false[医]类型%29{}模板<class T>空重抛[医]如果[医]嵌套%28 const T&t%29{详细信息::重新抛出[医]如果[医]巢式[医]IMPLE%28t,详细信息::CAN[医]动态[医]铸造<T>%28%29%29;}

*。

演示通过嵌套异常对象进行的构造和递归。

二次

代码语言:javascript
复制
#include <iostream>
#include <stdexcept>
#include <exception>
#include <string>
#include <fstream>
 
// prints the explanatory string of an exception. If the exception is nested,
// recurses to print the explanatory of the exception it holds
void print_exception(const std::exception& e, int level =  0)
{
    std::cerr << std::string(level, ' ') << "exception: " << e.what() << '\n';
    try {
        std::rethrow_if_nested(e);
    } catch(const std::exception& e) {
        print_exception(e, level+1);
    } catch(...) {}
}
 
// sample function that catches an exception and wraps it in a nested exception
void open_file(const std::string& s)
{
    try {
        std::ifstream file(s);
        file.exceptions(std::ios_base::failbit);
    } catch(...) {
        std::throw_with_nested( std::runtime_error("Couldn't open " + s) );
    }
}
 
// sample function that catches an exception and wraps it in a nested exception
void run()
{
    try {
        open_file("nonexistent.file");
    } catch(...) {
        std::throw_with_nested( std::runtime_error("run() failed") );
    }
}
 
// runs the sample function above and prints the caught exception
int main()
{
    try {
        run();
    } catch(const std::exception& e) {
        print_exception(e);
    }
}

二次

产出:

二次

代码语言:javascript
复制
exception: run() failed
 exception: Couldn't open nonexistent.file
  exception: basic_ios::clear

二次

另见

nested_exception (C++11)

a mixin type to capture and store current exceptions (class)

throw_with_nested (C++11)

throws its argument with std::nested_exception mixed in (function template)

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com