c++ - 如何做我自己的自定义运行时错误类?

标签 c++ exception

我正在尝试做一个简单的自定义 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 block

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

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

欢迎所有想法。 谢谢!

最佳答案

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

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

关于c++ - 如何做我自己的自定义运行时错误类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3688347/

相关文章:

python - 我应该对 Python 中的错误/非法参数组合提出哪个异常?

c++ - 使用临时变量 C++ 反转数组

c++ - 获取进程的基地址

c++ - 错误 C2440 : '=' : cannot convert from 'int *' to 'int **'

c++ - 为什么抛出局部变量调用 moves 构造函数?

c++ - 为什么在 C++ 中获得第一个 chace 异常

安卓。异常处理

c++ - 命令历史系统的最佳方法

c++ - 子类会影响虚拟方法的可见性吗?

objective-c - NSException 引发 :format: as the last statement in a method