您好,我目前的异常类/宏有问题。
所以首先是一个示例文件来说明我的意思。
#include <iostream>
#include <string>
class ExceptionHelper : public std::exception {
public:
ExceptionHelper(std::string msg) : std::exception(), msg_(msg) {}
ExceptionHelper operator<<(std::string const &value) {
msg_.append(" :: ");
msg_.append(value);
return ExceptionHelper(msg_);
}
virtual const char *what() const throw() { return msg_.c_str(); }
private:
std::string msg_;
};
#define DEFINE_EXCEPTION(ClassName, Message) \
class ClassName : public ExceptionHelper { \
public: \
ClassName(std::string msg = Message) : ExceptionHelper(msg) {} \
};
DEFINE_EXCEPTION(Test, "Testmessage")
int main() {
try {
throw Test();
} catch (Test &e) {
std::cout << "I was caught 1 " << e.what() << std::endl;
}
try {
throw(Test() << "Something added");
} catch (Test &e) {
std::cout << "I was caught 2 " << e.what();
} catch (std::exception &e) {
std::cout << "should not be called " << e.what() << std::endl;
}
try {
Test t;
t << "Something added";
throw t;
} catch (Test &e) {
std::cout << "I was caught 3 " << e.what();
} catch (std::exception &e) {
std::cout << "should not be called2" << e.what() << std::endl;
}
}
<< 运算符的不同版本(对输出没有影响):
ExceptionHelper& operator<<(std::string const &value) {
msg_.append(" :: ");
msg_.append(value);
return *this;
}
ExceptionHelper operator<<(std::string const &value) {
msg_.append(" :: ");
msg_.append(value);
return *this;
}
输出:
I was caught 1 Testmessage
should not be called Testmessage :: Something added
I was caught 3 Testmessage :: Something added
想要的输出:
I was caught 1 Testmessage
I was caught 2 Testmessage :: Something added
I was caught 3 Testmessage :: Something added
所以我想用我的 DEFINE_EXCEPTION 宏创建特殊异常类,效果很好。
我现在想向新的异常类型添加额外的信息。 (这对于调试很方便,因为它允许我编写类似 throw Test() << "Variable x : "+ std::to_string(x))
这在 main 方法中的情况 2 中显示。这里只捕获 std::exception 而不是 Test 异常。
如果我像在主要的第三个例子中那样做,它工作正常。
我在 << 运算符上尝试了很多样式,但我发现没有哪个会产生影响。
我会对允许该语法的解决方案感兴趣。也欢迎提供为什么这不起作用的信息。
最佳答案
感谢您的提示 :)...漫长的一天。
如果有人对工作版本感兴趣,请点击此处。
class ExceptionHelper : public std::exception {
public:
ExceptionHelper(std::string msg) : std::exception(), msg_(msg) {}
virtual const char *what() const throw() { return msg_.c_str(); }
protected:
std::string msg_;
};
#define DEFINE_EXCEPTION(ClassName, Message) \
class ClassName : public ExceptionHelper { \
public: \
ClassName(std::string msg = Message) : ExceptionHelper(msg) {} \
\
template<class T> \
ClassName &operator<<(T const &value) { \
msg_.append(" :: "); \
msg_.append(value); \
return *this; \
} \
};
关于c++ - C++::自定义异常,未捕获变量消息(<< 运算符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50744585/