#include <fstream>
#include <iostream>
#include <stdexcept>
using namespace std;
class FileNotFound: public logic_error
{
public:
explicit FileNotFound(const string& _Message):logic_error(_Message){}
};
int main()
{
try
{
ifstream file;
file.open("NoExistingFile");
if (file.fail())
throw FileNotFound("");
}
catch(const FileNotFound &e)
{
cout << "FileNotFound" << e.what();
}
catch(const exception &e)
{
cout << e.what();
}
return 0;
}
输出:FileNotFound
它是干净的代码(罗伯特·马丁)吗? std::exception 不提供“错误位置”。 清洁代码敏捷软件工艺手册(罗伯特·马丁)-> 第 7 章:错误处理-> 提供异常上下文
最佳答案
考虑到引用的段落,它肯定是不干净的,因为你只是得到了发生了什么的信息,但你没有得到异常抛出的地方的信息,因此你无法追溯调试。
我建议不要使用标准异常,而是使用 boost exceptions ,因为它们可以提供引发异常的上下文。
关于c++ - 它是干净的代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13719942/