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

后端 未结 13 847
遥遥无期
遥遥无期 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:37

    When I used to teach C++, our standard explanation was that they allowed you to avoid tangling sunny-day and rainy-day scenarios. In other words, you could write a function as if everything would work ok, and catch the exception in the end.

    Without exceptions, you would have to get a return value from each call and ensure that it is still legitimate.

    A related benefit, of course, is that you don't "waste" your return value on exceptions (and thus allow methods that should be void to be void), and can also return errors from constructors and destructors.

提交回复
热议问题