c++ - C++中的自定义异常,用于对函数的无效输入

标签 c++ c++11 error-handling

我想用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/

相关文章:

c++ - 像素着色器 | Directx 9 |使用像素着色器的索引图像 |如何使用 2 个纹理,第一个纹理作为图像,第二个作为索引图像

c++ - 将 gprof 与套接字一起使用

C++ 调试帮助内存泄漏

c++ - 为什么 C++03 文件流不接受字符串构造函数参数?

excel - VBA Excel 错误处理 - 特别是在函数中 - 专业 Excel 开发风格

r - 使用for回路和georoute计算行驶距离时跳过错误

使用死亡钻石进行 C++ 打印

multithreading - 当我在 32bit-ubuntu-12.04 下使用 g++4.7.0 测试 c++11 的新 <thread> 功能时,收到一条 'pure virtual method called' 消息

C++通用引用和LRef参数的类型推导

iphone - 使用 fatsecret food api 时出现无效的 oauth 签名错误