是干净的代码吗?
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 异常,因为它们可以提供引发异常的上下文。
更根本的问题是:为什么要首先使用异常?如果这是非异常行为(如果可以预期文件可能不存在),则根本不应引发异常。相反,控制应该沿着"官方路径"流动。
附加组件:在引用的书籍部分的意义上,它并不干净(因为没有提供定位问题所需的上下文例外 - 正如其他人所提到的),但也因为:
- 自定义异常用于操作控制流。
所以代替:
throw FileNotFound(""); } catch(const FileNotFound &e) {
只做:
cout << "FileNotFound" << e.what();
变量名称"e"并不是不言自明的,也不应该重复。
异常类应有自己的文件。
您不应该交替使用错误和异常(在您的问题中)。 恕我直言,这是一个额外的提示。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么在这个代码结束循环中没有得到结束
- 在c代码之间共享数据的最佳方式
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值