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

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

问题描述

我正在开发一个生成设备报告的库.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. 生成报告时出错

哪种错误处理机制最适合这些错误?

Which error-handling mechanism is best for these errors?

  • 只返回 truefalse
  • 返回错误代码
  • 断言并记录
  • 抛出异常
  • 以上任意组合

一些上下文信息:正常的工作流程如下.用户激活设备,从列表中选择报告并点击生成".

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? :)

推荐答案

其中任何一个都有不同的目的:

Any of these have different purposes:

  • 错误代码版本异常(s):异常和错误代码代表如何处理结果代码的不同习语.异常更加健壮——结果代码可以被忽略或丢失.一个库通常应该强烈区分在哪里/什么异常被抛出,以及何时使用错误代码.充其量,只使用两者之一.

  • 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.

return truefalse:错误代码的特殊化.通常是最糟糕的想法 - 只有在没有更多报告好或坏的情况下才好(即 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".

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

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