2

I have the following code in which dbh constructor may throw exception. The question I have is, dbh is declared inside try block. Will it be available after the catch? If yes, are there any other exceptions where the scope resolution is different than {} ? If not, what is the best design alternative?

status func(const char* field, char** value)
{
    try {
        dbhandler<recType> dbh(("dbName"),("table"));
    }
    catch (std::runtime_error &e) {
        LOG_ERR << e.what() << endl ;
        return false;
    }
    catch (...) {
        LOG_ERR << "Unknown exception" << endl ;
        return false;
    }

    rc = dbh.start("key",field, val);
    return rc;
}
4

2 回答 2

8

抓到后能用吗?

不,它将在声明它的块的末尾被销毁,就像任何其他局部变量一样。

try {
    dbhandler<recType> dbh(("dbName"),("table")); 
}   // dbh.~dbhandler<recType>() is called to destroy dbh

最好的设计方案是什么?

dbh在块外声明try或将所有使用它的代码移到try块中。哪一个最有意义取决于您的具体用例。

在一些相关的说明中,如果您catch (...)应该重新抛出异常或终止应用程序:您不知道正在处理什么异常,并且通常您不知道继续执行是否安全。

于 2011-02-25T17:34:21.750 回答
2

根据您的功能代码,这样编写它很有意义:

status func(const char* field, char** value)
{
    try {
        dbhandler<recType> dbh(("dbName"),("table"));
        status rc = dbh.start("key",field, val);
        return rc;
    }
    catch (std::runtime_error &e) {
        LOG_ERR << e.what() << endl ;
        return false;
    }
    catch (...) {
        LOG_ERR << "Unknown exception" << endl ;
        return false;
    }
}
于 2011-02-25T17:41:34.373 回答