Опитвам се да отпечатам вложени изключения, като използвам следния примерен код от cppreference.com :
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(...) {}
}
Получавам обаче прекъсване, ако най-вътрешното изключение е std::nested_exception
, а не std::exception
(т.е. хвърлям std::nested_exception
, хващам го и след това прилагам print_exception
).
Това е минимален пример:
int main() {
try {
std::throw_with_nested( std::runtime_error("foobar") );
} catch(const std::exception& e1) {
std::cerr << e1.what() << std::endl;
try {
std::rethrow_if_nested(e1);
} catch( const std::exception& e2 ) {
std::cerr << e2.what() << std::endl;
} catch( ... ) {
}
} catch ( ... ) {
}
}
Той прекъсва:
foobar
terminate called after throwing an instance of 'std::_Nested_exception<std::runtime_error>'
what(): foobar
Aborted (core dumped)
В документацията за std::throw_with_nested
се посочва, че
Конструкторът по подразбиране на базовия клас nested_exception извиква std::current_exception, улавяйки текущо обработвания обект на изключение, ако има такъв, в std::exception_ptr
така че бих очаквал e1
да произлиза от std::nested_exception
, но нямам nested_ptr
. Защо std::rethrow_if_nested
не се справя с това? Какъв е най-добрият подход за мен да се справя с този случай?
std::rethrow_if_nested
ще извика rethrow_nested, което извикваstd::terminate
, когато нямаnested_ptr
, вие може да направи еквивалента ръчно. - person Jarod42   schedule 21.10.2016