Determining exception type after the exception is caught?
Solution 1:
Short Answer: No.
Long Answer:
If you derive all your exceptions from a common base type (say std::exception) and catch this explicitly then you can use this to get type information from your exception.
But you should be using the feature of catch to catch as specific type of exception and then working from there.
The only real use for catch(...) is:
- Catch: and throw away exception (stop exception escaping destructor).
- Catch: Log an unknwon exception happend and re-throw.
Edited: You can extract type information via dynamic_cast<>() or via typid() Though as stated above this is not somthing I recomend. Use the case statements.
#include <stdexcept>
#include <iostream>
class X: public std::runtime_error // I use runtime_error a lot
{ // its derived from std::exception
public: // And has an implementation of what()
X(std::string const& msg):
runtime_error(msg)
{}
};
int main()
{
try
{
throw X("Test");
}
catch(std::exception const& e)
{
std::cout << "Message: " << e.what() << "\n";
/*
* Note this is platform/compiler specific
* Your milage may very
*/
std::cout << "Type: " << typeid(e).name() << "\n";
}
}
Solution 2:
You can actully determine type inside a catch(...), but it is not very useful:
#include <iostream>
#include <exception>
class E1 : public std::exception {};
class E2 : public std::exception {};
int main() {
try {
throw E2();
}
catch( ... ) {
try {
throw;
}
catch( const E1 & e ) {
std::cout << "E1\n";
}
catch( const E2 & e ) {
std::cout << "E2\n";
}
}
}