如何抛出std ::异常与可变消息? [英] Howto throw std::exceptions with variable messages?
本文介绍了如何抛出std ::异常与可变消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是一个例子,当我想添加一些信息到一个异常,我经常做的
std :: stringstream errMsg;
errMsg<< 无法加载配置文件< configfile<< ';
throw std :: exception(errMsg.str()。c_str());有没有更好的方法?
h2_lin>解决方案
这是我的解决方案:
class Formatter
{
public:
Formatter(){}
〜Formatter(){}
template< typename Type>
Formatter&运算符<< (const Type& value)
{
stream_<<值;
return * this;
}
std :: string str()const {return stream_.str(); }
operator std :: string()const {return stream_.str(); }
enum ConvertToString
{
to_str
};
std :: string operator>> (ConvertToString){return stream_.str(); }
private:
std :: stringstream stream_;
Formatter(const Formatter&);
Formatter& operator =(Formatter&);
};
示例:
code> throw std :: runtime_error(Formatter()<< foo<< 13<<,bar<< myData); // implicitly cast to std :: string
throw std :: runtime_error(Formatter()<< foo<< 13<<,bar<< myData> Format :: to_str); //显式转换为std :: string
This is an example of what I often do when I want to add some information to an exception:
std::stringstream errMsg;
errMsg << "Could not load config file '" << configfile << "'";
throw std::exception(errMsg.str().c_str());
Is there a nicer way to do it?
解决方案
Here is my solution:
class Formatter
{
public:
Formatter() {}
~Formatter() {}
template <typename Type>
Formatter & operator << (const Type & value)
{
stream_ << value;
return *this;
}
std::string str() const { return stream_.str(); }
operator std::string () const { return stream_.str(); }
enum ConvertToString
{
to_str
};
std::string operator >> (ConvertToString) { return stream_.str(); }
private:
std::stringstream stream_;
Formatter(const Formatter &);
Formatter & operator = (Formatter &);
};
Example:
throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData); // implicitly cast to std::string
throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData >> Formatter::to_str); // explicitly cast to std::string
这篇关于如何抛出std ::异常与可变消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文