在线文档教程
C++
应用 | Utilities

std::throw_with_nested

STD:扔[医]带着[医]巢式

Defined in header
template< class T > [noreturn] void throw_with_nested( T&& t (since C++11)

如果std::decay<T>::type是一个非最终的非联合类类型,两者都不是。std::nested_exception也不是从std::nested_exception引发一个未指定类型的异常,该异常是公开从这两个类型派生的。std::nested_exception和来自std::decay<T>::type,并由std::forward<T>(t)的默认构造函数。nested_exception基类调用std::current_exception中捕获当前处理的异常对象(如果有的话)。std::exception_ptr...

否则,抛出std::forward<T>(t)...

要求std::decay<T>::type是CopyConstructible...

参数

t-the exception object to throw

返回值

%280%29

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

二次

#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 } }

二次

产出:

二次

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)
rethrow_if_nested (C++11)throws the exception from a std::nested_exception (function template)

© cppreference.com

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

http://en.cppreference.com/w/cpp/Error/PUT[医]带着[医]巢式