c++ - 它是干净的代码吗?

标签 c++ error-handling coding-style

#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/

相关文章:

java - 迭代集合时检查可为空性

php - 允许 fckeditor 2 中的样式属性与 php 集成

python - 使用 if 条件列表理解

c++ - VS 2010 中的 PreFast?

c++ - 使用 OpenCV 模糊保存的检测对象图像

swift - 如何将此函数转换为throwing函数?

c# - WPF,带有错误和警告消息的句柄

c++覆盖一个已经定义的变量

c++ - 从我的 C++ 中的变量中删除 'const' 会导致我以后出现问题吗?

javascript - 在没有自定义错误处理程序的情况下隐藏 JS 错误