简体   繁体   English

这是干净的代码吗?

[英]Is it clean code?

#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;
}

Output: FileNotFound 输出:FileNotFound

Is it Clean code (Robert Martin)? 这是干净的代码(罗伯特马丁)? std::exception not provide "location of an error". std :: exception不提供“错误的位置”。 Clean Code A Handbook of Agile Software Craftsmanship (Robert Martin) -> Chapter 7: Error Handling -> Provide Context with Exceptions 清洁代码敏捷软件工艺手册(罗伯特马丁) - >第7章:错误处理 - >提供具有例外的上下文

Considering the quoted paragraph, it is certainly not clean, because you just get the information of what happened, but you do not get the information from where the exception was thrown, therefore you can not trace it back for debugging. 考虑到引用的段落,它肯定不干净,因为您只是获取所发生事件的信息,但是您没有从抛出异常的位置获取信息,因此您无法追溯它以进行调试。

Instead of using standard exceptions, I would advise to use boost exceptions , since they can provide the context from where the exception is thrown. 我建议使用boost异常 ,而不是使用标准异常,因为它们可以提供抛出异常的上下文。

The more fundamental question is: Why use an exception in the first place? 更基本的问题是:为什么首先使用例外? If it's a non-exceptional behavior (if it can be expected that a file might not be present), than no exception should be thrown at all. 如果它是非异常行为(如果可以预期文件可能不存在),则应该抛出任何异常。 Instead control should flow along an "official path". 相反,控制应该沿着“官方路径”流动。

Add-on: It is not clean in the sense of the quoted book section (because the context needed to locate the problem is not provided with the exception -as others have mentioned) but also because: 附加组件:从引用的书籍部分来看它并不干净(因为找不到问题的上下文没有提供例外 - 正如其他人提到的那样)但也因为:

  1. The custom exception is used to manipulate control flow. 自定义异常用于操纵控制流。

So instead of : 所以代替:

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

Do only: 只做:

    cout << "FileNotFound" << e.what(); 
  1. The variable name 'e' is not really self explanatory and should also not be repeated. 变量名'e'实际上不是自解释的,也不应该重复。

  2. The exception class should have its own file. 异常类应该有自己的文件。

  3. You should not use error and exception interchangably (in your question). 您不应该可互换地使用错误和异常(在您的问题中)。 This is an extra tipp imho. 这是一个额外的tipp imho。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM