Namespaces
Variants

std:: nested_exception

From cppreference.net
헤더 파일에 정의됨 <exception>
class nested_exception ;
(C++11부터)

std::nested_exception 는 현재 예외를 캡처하고 저장할 수 있는 다형성 믹스인 클래스로, 임의의 타입 예외들을 서로 중첩시킬 수 있게 합니다.

std::nested_exception 의 모든 멤버 함수는 constexpr 입니다.

(C++26부터)

목차

멤버 함수

nested_exception을 생성함
(public member function)
[virtual]
nested exception을 소멸시킴
(virtual public member function)
nested_exception의 내용을 교체함
(public member function)
저장된 예외를 다시 던짐
(public member function)
저장된 예외에 대한 포인터를 얻음
(public member function)

비멤버 함수

인자를 std::nested_exception 과 함께 던짐
(함수 템플릿)
std::nested_exception 에서 예외를 다시 던짐
(함수 템플릿)

참고 사항

기능 테스트 매크로 표준 기능
__cpp_lib_constexpr_exceptions 202411L (C++26) constexpr 예외 타입

예제

중첩된 예외 객체를 통한 생성 및 재귀를 보여줍니다.

#include <exception>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>
// prints the explanatory string of an exception. If the exception is nested,
// recurses to print the explanatory string 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& nestedException)
    {
        print_exception(nestedException, 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

참고 항목

예외 객체를 처리하기 위한 공유 포인터 타입
(typedef)
인자를 std::nested_exception 과 함께 던짐
(function template)
std::nested_exception 에서 예외를 다시 던짐
(function template)