【发布时间】:2014-02-26 02:46:38
【问题描述】:
我正在编写一个函数wd_sprintf,以提供类似 sprintf 的 API。在幕后,它使用了 boost 库。
如果wd_sprintf的用户对格式字符串编码不正确,boost::format会抛出异常。我想让我的函数拦截异常,将其重新打包到一条消息中,将wd_sprintf 标识为错误的位置,然后重新抛出异常。
我不知道要捕获什么,以及如何提取消息。
// wd_sprintf(pattern [,args...]):
//
// This creates a temporary boost::format from pattern, and calls
// wd_sprintf_r() to recursively extract and apply arguments.
#include <boost/exception/all.hpp>
class wd_sprintf_exception : std::runtime_error {
public:
wd_sprintf_exception(string const& msg : std::runtime_error(msg) {}
};
template <typename... Params>
string
wd_sprintf (const string &pat, const Params&... parameters) {
try {
boost::format boost_format(pat);
return wd_sprintf_r(boost_format, parameters...);
}
catch (boost::exception e) {
const string what = string("wd_sprintf: ") + string(e.what());
throw wd_sprintf_exception(what);
}
}
当然,这会产生编译错误,因为 boost::exception 是抽象的。
(我去过很多网站和页面,包括this one,其标题相似,但充满了插入函数调用的“boost::get_error_info<my_tag_error_info>(e) 之类的模板结构,以及通常很多比我想象的更复杂。我只需要上面的工作。)
【问题讨论】:
-
你应该永远是catching by reference。
boost::exception(和 C++ 标准库)就是这样设计的。
标签: c++ exception boost try-catch