【发布时间】:2013-05-29 15:55:22
【问题描述】:
例如,我有一些带有Load() 函数的课程。
class DB {
private:
pt_db *db;
public:
DB(const char *path);
Write(const char *path);
int Load(const char *path);
};
我想根据传递的参数从 Load() 函数返回一些状态。
例如:
Load(<correct path to the file with valid content>) // return 0 - success
Load(<non-existent path to file>) // return 1
Load(<correct file path, but the content of the file is wrong>) // return 2
不过我也很担心:
-
类型安全 - 我的意思是我想返回一些只能用作状态码的对象。
int res = Load(<file path>); int other = res * 2; // Should not be possible -
仅使用预定义的值。使用
int,我可以错误地返回一些其他状态,例如return 3(让我们建议Load()函数中发生了错误),如果我不希望这个错误代码会被传递:int res = Load(<file path>); if(res == 1) {} else if (res == 2) {}; ... // Here I have that code fails by reason that Load() returned non-expected 3 value 使用最佳 C++11 实践。
有人可以帮忙吗?
【问题讨论】:
-
enum class会这样做吗? -
异常是发出失败信号的常用方法。它们的优点是您不能(意外地)忽略它们并假设成功,并且它们可以编码尽可能多的信息。
-
我只是想知道一些可能的解决方案。为什么 C++11 有 std::error_code?另外我建议这段代码可以用在C代码中,C不能处理异常。
-
@user966467,无论如何,您都必须将其包装起来才能在 c 中使用它...
-
@user966467: 标准库使用
error_code以标准化方式报告系统错误,方法是抛出包含error_code的system_error。此外,您不能直接使用 C 中的代码,因为 C 也不能处理类。
标签: c++ c++11 error-handling