【问题标题】:Custom exception in C++ for invalid input to a functionC++ 中针对函数的无效输入的自定义异常
【发布时间】:2020-03-26 19:21:30
【问题描述】:

我想用 C++ 编写一个自定义错误类。我主要习惯于 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++ 中完成(以及最佳实践)。如果有更好的方法也欢迎告诉我。

【问题讨论】:

  • 与 Java 不同,在 C++ 中应谨慎使用异常。在 C++ 中抛出异常是昂贵的,并且应该只用于真正的异常情况。对于输入验证,通常只有在程序无法真正继续运行时才抛出异常。
  • 关于@Evg的评论,你也可以用struct代替class,因为默认情况下成员是public
  • @Someprogrammerdude 我认为人工输入太慢了(与计算速度相比),我不会担心过多的性能影响(在这种情况下)。
  • 请注意,C++ 有std::invalid_argument 异常。
  • @DanielsaysreinstateMonica 错误类看起来像是用于导致逻辑问题的输入。这种情况下输入错误不会导致逻辑错误,但不符合业务规则。

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


【解决方案1】:

为您的解决方案如下。

创建客户例外

class InvalidInput : public std::exception{

   public:
       InvalidInput(std::string msg):errorMsg_(msg){}   

   virtual const char* what() const throw()
   {
       return errorMsg_;
   }

   private:
       std::string errorMsg_;
};

使用该客户异常

myFunc(int x) {
    if (valueIsInvalid(x)) {
         throw InvalidInput ("invlaid input");
    }
}

【讨论】:

  • 您可以通过提及可以const char* what() override来完成您的答案
猜你喜欢
  • 2020-06-06
  • 2015-10-22
  • 2013-10-11
  • 1970-01-01
  • 2010-12-09
  • 1970-01-01
  • 2022-08-13
  • 1970-01-01
  • 2021-08-03
相关资源
最近更新 更多