c++ - 如何抛出带有可变消息的std::exceptions?

标签 c++ exception exception-handling

这是我要向异常中添加一些信息时经常执行的示例:

std::stringstream errMsg;
errMsg << "Could not load config file '" << configfile << "'";
throw std::exception(errMsg.str().c_str());

有更好的方法吗?

最佳答案

这是我的解决方案:

#include <stdexcept>
#include <sstream>

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 &);
};

例:
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

关于c++ - 如何抛出带有可变消息的std::exceptions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62705799/

相关文章:

ios - TableView : Terminating app due to uncaught exception 'NSInternalInconsistencyException' Error

java - 输入不匹配异常

.net - 如何处理其他线程上的错误?

c++ - catch(...) 没有捕获异常,我的程序仍然崩溃

c# - 如果在 using 语句中发生异常,对象是否仍会被释放?

c++ - ISO-8859 到 UTF-8 的转换 C++

c++ - 将可变参数模板模板参数专用于最小参数数量 : legal or not?

c++ - 我的代码似乎什么都不做

c++ - Windows 上的临时文件和文件夹

Python - 语法错误 'Exception'