【发布时间】:2015-12-09 10:54:45
【问题描述】:
我有以下代码:
#include <exception>
class Exception : public std::exception {
private:
const char* MESSAGE = "Exception"
public:
inline virtual const char* what() const throw() {
return this->MESSAGE;
}
};
class ShoulderROMException : public Exception {
private:
typedef Exception super;
const char* MESSAGE = "ShoulderROM exception";
protected:
static const int MAX_MESSAGE_LENGTH = 200;
mutable char composedMessage[ShoulderROMException::MAX_MESSAGE_LENGTH];
public:
virtual const char* what() const throw() {
strcpy(this->composedMessage, super::what());
strcat(this->composedMessage, " -> ");
strcat(this->composedMessage, this->MESSAGE);
return this->composedMessage;
}
};
class KinectInitFailedException : public ShoulderROMException {
private:
typedef ShoulderROMException super;
const char* MESSAGE = "Kinect initialization failed."
public:
virtual const char* what() const throw() {
strcpy(this->composedMessage, super::what());
strcat(this->composedMessage, " -> ");
strcat(this->composedMessage, this->MESSAGE);
return this->composedMessage;
}
};
这会产生如下所示的日志条目:
Exception -> ShoulderROM exception -> Kinect initialization failed.
这正是我想要的,但我想避免明显的代码重复,并且似乎找不到一种(n 优雅的)方法来做到这一点。
如果有人可以在这里帮助我,那就太好了。 :)
最好的问候, 莉萝
【问题讨论】:
-
多次调用
what目前会以奇怪的方式失败。您是否考虑过使用嵌套异常?由于异常安全与内存分配,您是否使用字符数组而不是字符串? -
你考虑过boost.exceptions吗?
-
是的,我认为 boost 和几个项目相关的原因不允许我使用它。另外,我不是 boost 的好朋友。我没有使用字符串,因为
std::exception强制使用char*类型。 -
我不太明白“
std::exception强制类型为char*”是什么意思。我所知道的std::exception和char*之间的唯一关系是std::exception::what,它返回一个char const*。但是可以将std::string数据成员存储在std::exception中,并使用std::string::c_str从std::exception::what返回char const*。std::string的问题是动态内存分配,但这在实践中不一定是一个问题,有时可以通过使用std::runtime_error来避免。
标签: c++ exception duplicates code-duplication generalization