问题
I am using mysql c++ connector with this (a bit simplified) code.
try
{
statement->setString(1, word);
statement->executeUpdate();
}
catch( sql::SQLException& e )
{
// I don't get here
return sqlerrno_to_error_code( e.getErrorCode() );
}
catch( std::exception& e )
{
// I do get here and the cast works
sql::SQLException& sqle = (sql::SQLException&) e;
return sqlerrno_to_error_code( sqle.getErrorCode() );
}
The connector is supposed to throw the sql::SQLException which derives from std::exception and has some additional methods like getErrorCode().
The exception thrown is caught in the second catch block, but can be cast to (and used as)sql::SQLException successfully.
Even more weird is that a similar code in a different executable catches sql::SQLException as expected. The difference between them is that the first one is in a shared object (.so) that is loaded with dlopen().
RHEL 5.7 32 bit, gcc 4.1.2
回答1:
See the note for dynamic_cast, throw, typeid don't work with shared libraries on the GCC Frequently Asked Questions page.
Because you are using dlopen(), you need to link your executable with the -E flag (or pass-Wl,-E to g++ if g++ is invoking the linker) and pass the RTLD_GLOBAL flag to dlopen().
来源:https://stackoverflow.com/questions/12387313/weird-mysqls-sqlsqlexception-is-not-caught-by-its-type-but-is-caught-as-st