【问题标题】:How to do my own custom runtime error class?如何做我自己的自定义运行时错误类?
【发布时间】:2010-09-10 21:06:26
【问题描述】:

我正在尝试做一个简单的自定义 runtime_error。我定义类:

#include <string>
#include <stdexcept>


namespace utils{

 class FileNotFoundException: public std::runtime_error{
  public:
   FileNotFoundException():runtime_error("File not found"){}
   FileNotFoundException(std::string msg):runtime_error(msg.c_str()){}
 };

};

然后我抛出错误:

bool checkFileExistence( std::string fileName )
 {
  boost::filesystem::path full_path = boost::filesystem::system_complete(boost::filesystem::path(fileName));
  if (!boost::filesystem::exists(full_path))
  {
    char msg[500];
    _snprintf(msg,500,"File %s doesn't exist",fileName.c_str());
    throw new FileNotFoundException(msg);
  }
 }

我使用了 try/catch 块

    try{
          checkFileExistence(fileName);
     }
   catch(utils::FileNotFoundException& fnfe)
        {
          std::cout << fnfe.what() << std::endl;
     }

运行时错误被正确抛出为 FileNotFoundException,但从未到达带有 std::cout 的行,并且没有将任何行写入控制台。

欢迎所有想法。 谢谢!

【问题讨论】:

  • 您可能希望使用默认参数而不是在您的异常类中覆盖。

标签: c++ exception


【解决方案1】:

那是因为你在抛出一个指针。只需:throw FileNotFoundException(msg);

每当您使用指针时,除非您将其放入容器/包装器中,否则您可能没有做正确的事情。

【讨论】:

    【解决方案2】:

    你写throw new FileNotFoundException(msg),应该是'throw FileNotFoundException(msg)'。规则是按值抛出,按引用捕获。

    【讨论】:

    • 除非您是使用 MFC 的 Microsoft,否则规则是按指针抛出并按指针捕获。他们在完全支持标准 throw/catch 之前创建了异常类,这导致了一些有趣的妥协。
    【解决方案3】:

    您实际上是在抛出一个指向堆分配对象 (FileNotFoundException*) 的指针,因此类型不匹配。通常,按值抛出并按引用捕获 (rule 73)。

    【讨论】:

      【解决方案4】:

      顺便说一句,通过以下声明,您可以创建 msg 字符串的副本。

      FileNotFoundException(std::string msg):runtime_error(msg.c_str()){}
      

      改为写“const std::string& msg”。它只会在堆栈上放置一个引用。而现在你把整个字符串放在一个堆栈上。

      【讨论】:

      • 已更正!感谢您的想法!
      猜你喜欢
      • 2013-04-24
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      • 1970-01-01
      • 2016-07-27
      • 2020-08-13
      • 2022-01-02
      • 2016-07-15
      相关资源
      最近更新 更多