我正试图找出如何能够写这样的东西:
try{
throw MyCustomException;
}
catch(const MyCustomException &e){
cout<< e;
}
但是如何为这个目的定义overloaded operator <<
呢?
自定义异常类:
class MyCustomException{
public:
MyCustomException(const int& x) {
stringstream ss;
ss << x;
msg_ = "Invalid index [" + ss.str() + "]";
}
string getMessage() const {
return (msg_);
}
private:
string msg_;
};
老实说,我认为正确的解决方案是遵循标准约定,使MyCustomException
从std::exception
派生。然后,您将实现what()
虚拟成员函数来返回消息,并且您最终可以通过operator <<
将该字符串插入标准输出。
你的异常类应该是这样的:
#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();
}
}
最后是一个实例