【问题标题】:Where do I put C++ Custom Exception Code?我在哪里放置 C++ 自定义异常代码?
【发布时间】:2018-09-27 20:16:27
【问题描述】:

我正在为我编写的生成随机短语的类编写自定义异常。我是 C++ 新手,我想知道是否应该将异常放在 Classes 头文件、Classes .cpp 文件中,或者是否需要拆分声明和实现。

Eclipse 在 main() 方法中给我一个错误,指出:

error: 'FileException' does not name a type
  } catch (FileException& e) {

异常类看起来像:

class FileException : public std::exception {   
    public:
        const char* what() {
            return "File Could not be opened.";
        }
    }FileException;

对这个问题的任何想法将不胜感激,因为我非常困惑和困惑。

谢谢!

编辑:我还应该提一下,我只应该提交 2 个文件,类的 .cpp 文件和 .h 文件

【问题讨论】:

  • 为一个不例外的课程做你想做的事。
  • 我个人喜欢使用std::runtime_error 而不是自定义异常,因为我可以在抛出站点给它一个自定义消息,这样可以更容易地找出抛出异常的原因。

标签: c++ class exception header


【解决方案1】:

摆脱变量(您可能不需要它)或为类和变量使用不同的名称。

说明:

class FileException : public std::exception {   

FileException 是一个类。很酷。

public:
    const char* what() {
        return "File Could not be opened.";
    }
}FileException;

最后一位定义了一个名为 FileExceptionFileException 类型的变量,它替换了 FileException 类。和定义是一样的

class FileException : public std::exception {   
public:
    const char* what() {
        return "File Could not be opened.";
    }
};
FileException FileException;

标识符FileException 现在引用变量,您不能引用类。

【讨论】:

    猜你喜欢
    • 2021-12-18
    • 2014-01-04
    • 1970-01-01
    • 2010-12-27
    • 2015-07-25
    • 1970-01-01
    • 2011-11-30
    • 2012-04-16
    • 1970-01-01
    相关资源
    最近更新 更多