std:: rethrow_if_nested
From cppreference.net
|
헤더에 정의됨
<exception>
|
||
|
template
<
class
E
>
void rethrow_if_nested ( const E & e ) ; |
(C++11부터)
(C++26부터 constexpr) |
|
만약
E
가 다형 클래스 타입이 아니거나,
std::nested_exception
이
E
의 접근 불가능하거나 모호한 기본 클래스인 경우, 아무런 효과가 없습니다.
그렇지 않으면, 다음을 수행합니다
if (auto p = dynamic_cast<const std::nested_exception*>(std::addressof(e))) p->rethrow_nested();
목차 |
매개변수
| e | - | 다시 던질 예외 객체 |
참고 사항
많은 관련 함수들과 달리, 이 함수는 실제로 std:: exception_ptr 가 아닌 실제 예외 참조로 호출되도록 의도되었습니다.
| 기능 테스트 매크로 | 값 | 표준 | 기능 |
|---|---|---|---|
__cpp_lib_constexpr_exceptions
|
202411L
|
(C++26) | constexpr 예외 타입 |
가능한 구현
namespace details { template<class E> struct can_dynamic_cast : std::integral_constant<bool, std::is_polymorphic<E>::value && (!std::is_base_of<std::nested_exception, E>::value || std::is_convertible<E*, std::nested_exception*>::value) > {}; template<class T> void rethrow_if_nested_impl(const T& e, std::true_type) { if (auto nep = dynamic_cast<const std::nested_exception*>(std::addressof(e))) nep->rethrow_nested(); } template<class T> void rethrow_if_nested_impl(const T&, std::false_type) {} } template<class T> void rethrow_if_nested(const T& t) { details::rethrow_if_nested_impl(t, details::can_dynamic_cast<T>()); } |
예제
중첩된 예외 객체를 통한 생성 및 재귀를 보여줍니다.
이 코드 실행
#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
참고 항목
|
(C++11)
|
현재 예외를 캡처하고 저장하기 위한 믹스인 타입
(class) |
|
(C++11)
|
인자를
std::nested_exception
이 혼합된 상태로 throw
(function template) |