我想用C++写一个自定义的Error类。我大部分时间都习惯Java(不常使用Java),所以我想在这里检查一下我在C++中如何做到这一点的思想过程是否正确。
目前我得到以下代码:
class InvalidInput : public std::runtime_error {
public:
InvalidInput(const char* msg) : std::runtime_error(msg) {
}
};
我打算像这样在函数中使用cutsom错误:
myFunc(int x) {
if (valueIsInvalid(x)) {
throw InvalidInput ("invalid input");
}
}
在实现它之前,我想知道我是否在正确的方向上应该如何在C++中实现(以及最佳实践)。如果有更好的方法,请随时告诉我。
最佳答案
为您的解决方案如下。
create custome exception
class InvalidInput : public std::exception{
public:
InvalidInput(std::string msg):errorMsg_(msg){}
virtual const char* what() const throw()
{
return errorMsg_;
}
private:
std::string errorMsg_;
};
use of that custome excetion
myFunc(int x) {
if (valueIsInvalid(x)) {
throw InvalidInput ("invlaid input");
}
}
关于c++ - C++中的自定义异常,用于对函数的无效输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59134526/