【问题标题】:Overloading << operator for printing out custom exception [duplicate]重载 << 运算符以打印出自定义异常 [重复]
【发布时间】:2013-04-07 00:31:49
【问题描述】:

我正在尝试找出如何能够写出这样的东西:

try{
    throw MyCustomException;
}
catch(const MyCustomException &e){
cout<< e;
}

但是如何为此目的定义overloaded operator &lt;&lt;?

自定义异常类:

class MyCustomException{

public:

MyCustomException(const int& x) {
    stringstream ss;
    ss << x; 

    msg_ = "Invalid index [" + ss.str() + "]";
}

string getMessage() const {
    return (msg_);
}
private:
    string msg_;
};

【问题讨论】:

  • IMO 只做cout &lt;&lt; e.getMessage()
  • @LightnessRacesinOrbit 对不起,我的错误

标签: c++


【解决方案1】:

老实说,我相信正确的解决方案是遵循标准约定并让MyCustomException 派生自std::exception。然后,您将实现what() 虚拟成员函数以返回一条消息,您最终可以将该字符串通过operator &lt;&lt; 插入到标准输出中。

这就是你的异常类的样子:

#include <string>
#include <sstream>
#include <stdexcept>

using std::string;
using std::stringstream;

class MyCustomException : public std::exception
{
public:

    MyCustomException(const int& x) {
        stringstream ss;
        ss << x;
        msg_ = "Invalid index [" + ss.str() + "]";
    }

    virtual const char* what() const noexcept {
        return (msg_.c_str());
    }

private:

    string msg_;
};

下面是你将如何使用它:

#include <iostream>

using std::cout;

int main()
{
    try
    {
        throw MyCustomException(42);
    }
    catch(const MyCustomException &e)
    {
        cout << e.what();
    }
}

最后是live example。

【讨论】:

    猜你喜欢
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2013-08-15
    相关资源
    最近更新 更多