3

Possible Duplicate:
C++ - Arguments for Exceptions over Return Codes

While you are doing C++ programming, you have two choices of reporting an error. I suppose many teachers would suggest you throw an exception, which is derived from std::exception. Another way, which might be more "C" style, is to return a non-zero value, as zero is "ERROR_SUCCESS".

Definitively, return an exception can provide much more information of the error and recovery; while the code will bloat a little bit, and making exception-safe in your mind is a little difficult for me, at least. Other way like returning something else, will make reporting an error much easier; the defect is that managing recovery will be a possibly big problem.

So folks, as good programmers, which would be your preference, not considering your boss' opinion? For me, I would like to return some nonzero values.

Community
  • 1
  • 1
xis
  • 24,330
  • 9
  • 43
  • 59
  • 6
    Exceptions bloat the code? I'd think having a check for a nonzero return value after every function call is much more noise than a try-catch at some strategic place. – sth Jun 07 '10 at 23:40
  • See http://stackoverflow.com/questions/1849490/c-arguments-for-exceptions-over-return-codes , http://stackoverflow.com/questions/99683/which-and-why-do-you-prefer-exceptions-or-return-codes , etc. – Owen S. Jun 07 '10 at 23:42
  • 1
    yes, exceptions bloat the code. At least so think people from Google http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Exceptions#Exceptions go to Exceptions section – Tebe May 08 '13 at 18:47

3 Answers3

6

From the C++ FAQ: Use Exceptions for errors.

The logic behind this in my opinion, is that with return codes, the onus is up to the caller of your code to check return codes to handle errors. This then, allows users of your code to potentially get into a bad situation. Exceptions, on the other hand, must be dealt with, or they bubble up the call stack until it terminates the program.

In my opinion, if you are writing C++ (and wish to adhere to C++ idioms), and want to use error handling, exceptions are the way to go.

Alan
  • 45,915
  • 17
  • 113
  • 134
1

You might find Exception handling seems to make my life more difficult; clearly I'm not the problem, am I?? worth reading.

JRL
  • 76,767
  • 18
  • 98
  • 146
1

Error handling is much easier through exceptions most of the time. Writing exception safe code is also quite easy. I'm lazy. I take the easy route.

Edward Strange
  • 40,307
  • 7
  • 73
  • 125
  • Doesn't that actually cost more coding effort? You **do** check every return code, don’t you? As opposed to having a try/exception cover a code block, which would be one piece of error handling code as opposed to many. – Mawg says reinstate Monica Jun 03 '15 at 06:49