RTTI and catch(...)

L

lfnovaes

Is it possible to get the type of a "unknown" exception using RTTI?
Tanks in advance.
 
S

Salt_Peter

Is it possible to get the type of a "unknown" exception using RTTI?
Tanks in advance.

Not neccessarily, depends what you know about the thrown exception and
how you are capturing it.
If the unknown exception is derived from std::exception (or some other
base), then yes you could get its type since you'ld be catching the
exception using a base reference.

ie:

#include <iostream>
#include <typeinfo>
#include <stdexcept>

// std::runtime_error is derived from std::exception
class unknown_exception : public std::runtime_error
{
public:
unknown_exception() : std::runtime_error("unknown exception") { }
};

int main ()
{
try
{
throw unknown_exception();
}
catch( const std::exception& r_e )
{
std::cout << "std exception caught: ";
std::cout << r_e.what() << std::endl;
std::cout << "typename: ";
std::cout << typeid( r_e ).name() << std::endl;
}
catch(...) // catch-all
{
std:cout << "unexpected exception caught!\n:;
}
}

/*
std exception caught: unknown exception
typename: unknown_exception
*/

What might be thrown could me anything: an integer, an instance of a
user-type, a string, a long, or hopefully a derivative of
std::exception.

The goal is not to catch the exception in the above catch-all block
(you might have a try-catch block to isolate a problematic area at
which point you can rethrow a meaningfull exception).
 
J

James Kanze

Is it possible to get the type of a "unknown" exception using RTTI?

Not at present. I think that some sort of support for this is
being considered for future inclusion. (The compiler/run-time
obviously has the information, and it probably needed for things
like join.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top