In C++ what are the benefits of using exceptions and try / catch instead of just returning an error code?

后端 未结 13 880
遥遥无期
遥遥无期 2020-12-04 19:58

I\'ve programmed C and C++ for a long time and so far I\'ve never used exceptions and try / catch. What are the benefits of using that instead of just having functions retur

13条回答
  •  感动是毒
    2020-12-04 20:21

    I wrote a blog entry about this (Exceptions make for Elegant Code), which was subsequently published in Overload. I actually wrote this in response to something Joel said on the StackOverflow podcast!

    Anyway, I strongly believe that exceptions are preferable to error codes in most circumstances. I find it really painful to use functions that return error codes: you have to check the error code after each call, which can disrupt the flow of the calling code. It also means you can't use overloaded operators as there is no way to signal the error.

    The pain of checking error codes means that people often neglect to do so, thus rendering them completely pointless: at least you have to explicitly ignore exceptions with a catch statement.

    The use of destructors in C++ and disposers in .NET to ensure that resources are correctly freed in the presence of exceptions can also greatly simplify code. In order to get the same level of protection with error codes you either need lots of if statements, lots of duplicated cleanup code, or goto calls to a common block of cleanup at the end of a function. None of these options are pleasant.

提交回复
热议问题