异常与错误代码vs.断言 [英] Exception vs. error-code vs. assert

查看:430
本文介绍了异常与错误代码vs.断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个可生成设备报告的库。 generate_report(const std :: string& no)成员函数可能会由于各种原因失败:

I'm working on a library that generates reports of devices. The generate_report (const std::string& no) member function can fail due to various reasons:


  1. 无效报告号

  2. 无效状态( report_generator 是FSM)

  3. 没有设备处于活动状态

  4. 报告生成期间出现错误

  1. invalid report no.
  2. invalid state (the report_generator is a FSM)
  3. no device is active
  4. error during report generation

最好是这些错误?


  • 只需返回 true false

  • 返回错误代码

  • 断言并记录


  • 上述任何组合

  • just return true or false
  • return error code
  • assert and log
  • throw exception(s)
  • any combination of the above

某些上下文信息:正常工作流程如下。用户激活设备,从列表中选择报告,然后点击生成。

Some context information: the normal workflow is as following. The user activates a devices, chooses a report from a list and clicks on "generate".

编辑:感谢您的答复!对我来说很清楚,现在什么时候使用断言和什么时候做错误处理。至于错误处理,错误代码和异常都有优缺点。我想我去寻找异常(并为上述错误创建四个类),但我还没有真正相信。我总是想到意外情况的例外。一个无效的报告没有真正意想不到的。任何建议? :)

Thanks for the replies so far! For me it's clear now when to use asserts and when to do error-handling. As for error-handling, error codes and exceptions both have pros and cons. I think I go for exceptions (and create four classes for the above errors), but I'm not yet really convinced. I always thought of exceptions of 'unexpected situations'. An invalid report no isn't really unexpected. Any advice? :)

推荐答案

这些都有不同的目的:


  • 错误代码vers。异常:异常和错误代码表示结果代码如何处理的不同习语。异常更强大 - 结果代码可以被忽略或丢失。库通常应该强烈地区分哪里/什么异常被抛出,以及何时使用错误代码。

  • error code vers. exception(s): exceptions and error codes represent different idioms of how result codes shout be handled. Exceptions are more robust - result codes can be ignored or lost. A library should usually strongly distinguish where/what exceptions are thrown, and when error codes are used. At best, use only one of both at all.

返回 true false :错误代码的专门化。
通常最糟糕的想法 - 只有当没有更多的报告好或坏(即 malloc 返回好或坏(= NULL )。

return true or false: A specialization of error codes. Usually the worst idea - only good if there is no more to report than good or bad (i.e. malloc returns either good or bad (= NULL).

assert和log:这些是调试技术,不应该用作用户/ 。

assert and log: These are debugging techniques, and should not be used as report mechanisms to users / clients. Asserts just say "something happened, that I can not handle - I quit".

这篇关于异常与错误代码vs.断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆