#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 不提供“错误位置”。Clean Code A Handbook of Agile Software Craftsmanship (Robert Martin) -> 第 7 章:错误处理 -> 提供异常上下文