C++ - Arguments for Exceptions over Return Codes

后端 未结 11 1669
鱼传尺愫
鱼传尺愫 2020-11-29 21:10

I\'m having a discussion about which way to go in a new C++ project. I favor exceptions over return codes (for exceptional cases only) for the following reasons -

11条回答
  •  被撕碎了的回忆
    2020-11-29 21:33

    1. Constructors can't give a return code (except if you are possibly throwing exceptions in a constructor you are in for a world of hurt)

    2. Decouples the failure path (which should be very rare) from the logical code which is cleaner (Opens up a much wider failure path. C++ exceptions are not like C# at all. I love C# exceptions. C++ exceptions are worse than useless. Partly due to implementation, partly due to what c++ is and isn't)

    3. Faster in the non-exceptional case (no checking if/else hundreds of thousands of times) (Not really. You have to check the same number of errors no matter what, you just don't see where they get checked. Also, there are errors that matter and ones that don't or at least matter to your code, so you don't have to check every single thing (do you check to see if new threw an error?))
    4. If someone screws up the return code settings (forgets to return FAIL) it can take a very long time to track down. (I'll take a million such errors over any one of the common errors that come about with C++ exceptions)
    5. Better information from the message contained in the error. (It was pointed out to me that a return enum could do the same for error codes) (Well, how do you implement your error handling? That's up to you, isn't it? You can have exceptions that give no useful information or error codes that log out extemsive data on failure. In C++ they seem to never give useful info in the cases you really want them to)
    6. From Jared Par Impossible to ignore without code to specifically designed to handle it (Sure, but this code is usually useless code. It's like passing a law saying everyone has to have bug free programs. The people who don't don't obey such laws anyway and for the people who do they already handle errors where they should anyway)

    As for reasons against:

    1. Wanting your program to actually work at least some of the time.
    2. performance.
    3. Ideology. If it's an error we are not supposed to 'recover' from it. We either die with an error message, log and continue, or completely ignore it. If we could fix it it wouldn't be an error, but a feature...and if you use code like that intentionally no debugging tools in the world are going to save you.

    Mostly one.

提交回复
热议问题