Namespaces
Variants

std:: throw_with_nested

From cppreference.net
헤더에 정의됨 <exception>
template < class T >
[ [ noreturn ] ] void throw_with_nested ( T && t ) ;
(C++11부터)
(C++26부터 constexpr)

만약 std:: decay < T > :: type 가 final이 아니고 union이 아닌 클래스 타입이며 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 - 던질 예외 객체

참고 사항

기능 테스트 매크로 표준 기능
__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

참고 항목

현재 예외를 캡처하고 저장하기 위한 믹스인 타입
(class)
std::nested_exception 에서 예외를 다시 던짐
(function template)