c++设计问题尝试捕捉
我有以下代码,其中 dbh 构造函数可能会抛出异常。我的问题是,dbh 是在 try 块内声明的。捕获后可以使用吗?如果是,是否存在范围解析与 {} 不同的其他异常?如果不是,最好的设计方案是什么?
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不会。它会在声明它的块末尾被销毁,就像任何其他局部变量一样。
在
try
块之外声明dbh
或将使用它的所有代码移至try
块中。哪一种最有意义取决于您的具体用例。在某种程度上相关的说明中,如果您
catch (...)
,您应该重新抛出异常或终止应用程序:您不知道正在处理什么异常,并且通常您不知道是否继续执行是安全的。No. It will be destroyed at the end of the block in which it is declared, just like any other local variable.
Declare
dbh
outside of thetry
block or move all the code that uses it into thetry
block. Which one makes the most sense depends on your specific use case.On a somewhat related note, if you
catch (...)
, you should either rethrow the exception or terminate the application: you have no idea what exception is being handled and in general you have no idea whether it is safe to continue executing.根据你的函数代码,这样写很有意义:
According to your function code, it makes much sense to write it like that: