knivil
knivil

Reputation: 906

nested exceptions and primitive types

Can I use std::throw_with_nested when my captured exception is of primitive type?

It is said, that the new type is derived from the captured exception and the new exception. But I can not derive from primitives types like int. Therefore I can not use nested exceptions with primitive types. Is that true?

Upvotes: 1

Views: 129

Answers (3)

John5342
John5342

Reputation: 1149

The exception thrown is an unspecified type derived from the new exception and std::nested_exception (not the new and the captured). The std::nested_exception then contains a std::exception_ptr to the captured exception (obtained from std::current_exception).

So:

If the new exception is an int then you throw an int as other answers have stated.

If you capture an int then you throw (a type derived from) the new exception with the thrown int in the std::nested_exception.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477464

The standard says about throw_with_nested(T && t), with U = remove_reference<T>::type:

Throws: if U is a non-union class type not derived from nested_exception, an exception of unspecified type that is publicly derived from both U and nested_exception and constructed from std::forward<T>(t), otherwise std::forward<T>(t).

The "otherwise" clause seems to say that if you don't have a class type, you just throw the original argument.

Upvotes: 1

Igor Tandetnik
Igor Tandetnik

Reputation: 52611

My copy of the standard says this:

18.8.6/7 Throws: if U is a non-union class type not derived from nested_exception, an exception of unspecified type that is publicly derived from both U and nested_exception and constructed from std::forward<T>(t), otherwise std::forward<T>(t).

So throw_with_nested(42) should throw 42;

Upvotes: 1

Related Questions