Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

c++ - Exception vs. error-code vs. assert

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. invalid report no.
  2. invalid state (the report_generator is a FSM)
  3. no device is active
  4. error during report generation

Which error-handling mechanism is best for these errors?

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Any of these have different purposes:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...