我应该C++自定义异常代码放在哪里?

Where do I put C++ Custom Exception Code?

本文关键字:在哪里 代码 C++ 自定义异常 我应该      更新时间:2023-10-16

我正在为我编写的生成随机短语的类编写一个自定义异常。我是C++新手,我想知道我是否应该将异常放在类头文件、类.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文件

去掉变量(你可能不需要它(或为类和变量使用不同的名称。

解释:

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现在引用变量,而不能引用类。