C++11 exception features
#include <exception>
typedef exception_ptr;
template< class E >
std::exception_ptr make_exception_ptr( E e )
std::exception_ptr current_exception();
[[noreturn]] void rethrow_exception( std::exception_ptr p );
#include <iostream>
#include <string>
#include <exception>
#include <stdexcept>
void handle_eptr(std::exception_ptr eptr)
{
try
{
if (eptr != std::exception_ptr())
{
std::rethrow_exception(eptr);
}
}
catch(const std::exception& e)
{
std::cout << "Caught exception \"" << e.what() << "\"\n";
}
}
int main()
{
std::exception_ptr eptr;
try
{
std::string().at(1);
}
catch(...)
{
eptr = std::current_exception();
}
handle_eptr(eptr);
}
std::nested_exceptions is a polymorphic mixin class which can capture
and store the current exception, making it possible to nest exceptions
of arbitrary types within each other.
class nested_exception
{
public:
nested_exception();
~nested_exception();
nested_exception& operator=(const nested_exception&);
[[noreturn]] void rethrow_nested() const;
std::exception_ptr nested_ptr() const;
};
template< class T >
[[noreturn]] void throw_with_nested( T&& t );
template< class E >
void rethrow_if_nested( const E& e );
{
}
#include <iostream>
#include <stdexcept>
#include <exception>
#include <string>
#include <fstream>
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(...) {}
}
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) );
}
}
void run()
{
try
{
open_file("nonexistent.file");
}
catch(...)
{
std::throw_with_nested( std::runtime_error("run() failed") );
}
}
int main()
{
try
{
run();
}
catch(const std::exception& e)
{
print_exception(e);
}
}