是干净的代码吗?

Is it clean code?

本文关键字:代码      更新时间:2023-10-16
#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;
}

输出:文件未找到

是干净的代码(罗伯特马丁)吗?std::exception 不提供"错误位置"。Clean Code A Handbook of Agile Software Craftmanship (Robert Martin) -> 第 7 章:错误处理 -> 提供带有

异常的上下文

考虑到引用的段落,它肯定是不干净的,因为你只是得到了发生的事情的信息,但你没有从抛出异常的地方得到信息,因此你无法追溯它进行调试。

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

更根本的问题是:为什么要首先使用异常?如果这是非异常行为(如果可以预期文件可能不存在),则根本不应引发异常。相反,控制应该沿着"官方路径"流动。

附加组件:在引用的书籍部分的意义上,它并不干净(因为没有提供定位问题所需的上下文例外 - 正如其他人所提到的),但也因为:

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

所以代替:

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

只做:

    cout << "FileNotFound" << e.what(); 
  1. 变量名称"e"并不是不言自明的,也不应该重复。

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

  3. 您不应该交替使用错误和异常(在您的问题中)。 恕我直言,这是一个额外的提示。