这是干净的代码吗?

时间:2012-12-05 09:29:26

标签: 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

是清洁代码(Robert Martin)吗? std :: exception不提供“错误的位置”。 清洁代码敏捷软件工艺手册(Robert Martin) - &gt;第7章:错误处理 - &gt;提供具有例外的上下文

3 个答案:

答案 0 :(得分:3)

考虑到引用的段落,它肯定不干净,因为您只是获取所发生事件的信息,但是您没有从抛出异常的位置获取信息,因此您无法追溯它以进行调试。

我建议使用boost exceptions而不是使用标准异常,因为它们可以提供抛出异常的上下文。

答案 1 :(得分:0)

更基本的问题是:为什么首先使用例外?如果它是非异常行为(如果可以预期文件可能不存在),则应该抛出任何异常。相反,控制应沿着“官方路径”流动。

答案 2 :(得分:0)

附加组件:从引用的书本部分来讲,这并不干净(因为没有提供定位问题的上下文,就像其他人提到的那样),但这也是因为:

  1. 自定义异常用于操纵控制流。

所以不是:

   throw FileNotFound("");
 }
 catch(const FileNotFound &e)
 {

只能执行:

    cout << "FileNotFound" << e.what(); 
  1. 变量名'e'不能真正说明问题,也不应重复。

  2. 异常类应该具有自己的文件。

  3. 您不应互换使用错误和异常(在您的问题中)。这是额外的小费恕我直言。

相关问题