Is there a way to determine the exception type even know you caught the exception with a catch all?
Example:
try
{
SomeBigFunction();
}
catch(...)
This question was asked some time ago and I'm offering this answer as a companion to the accepted answer from 9 years ago. I'd have to concur with that respondent that that answer, "... is not very useful." Further, it opens the door to an exception which was once handled being unhandled. To illustrate, let me build upon the respondent's answer
#include
#include
class E1 : public std::exception {};
class E2 : public std::exception {};
class E3 : public std::exception {};
int main() {
try {
throw E3();
}
catch( ... ) {
try {
// OOOPS!!! E3 is now unhandled!!!!!!
throw;
}
catch( const E1 & e ) {
std::cout << "E1\n";
}
catch( const E2 & e ) {
std::cout << "E2\n";
}
}
}
An alternative to this approach would be the following:
#include
#include
class E1 : public std::exception {};
class E2 : public std::exception {};
class E3 : public std::exception {};
int main() {
try {
throw E3();
}
catch( const E1 & e ) {
std::cout << "E1\n";
}
catch( const E2 & e ) {
std::cout << "E2\n";
}
catch( ... ) {
std::cout << "Catch-all...";
}
}
This second approach seems to be tantamount to the first and has the advantage of specifically handling E1
and E2
and then catching everything else. This is offered only as an alternative.
Please note that, according to C++ draft of 2011-02-28, paragraph 15.3, bullet item 5, "If present, a ... handler shall be the last handler for its try block."