weird - mysql's sql::SQLException is not caught by its type, but is caught as std::exception and cast back successfully

℡╲_俬逩灬. 提交于 2019-12-30 11:51:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!