C++ - Arguments for Exceptions over Return Codes

后端 未结 11 1636
鱼传尺愫
鱼传尺愫 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:54

    Use exceptions for exceptional error conditions. You have some good arguments for, and I'd like to attack some arguments against.

    First, the standard C++ library uses exceptions itself, all over the place. You can't use container classes or iostreams without having them present. Since a lot of the useful features are going to use them, trying to get along without them is going to present a lot of problems.

    Second, it isn't hard to write exception-safe code once you've learned how to do it. It requires consistent RAII, but that's how you should write anyway. You should adopt a construct-commit approach, but that is frequently an advantage, and avoids some subtle bugs. (For example, the self-assignment problem disappears entirely with a copy-swap approach.) In my experience, exception-safe code looks better in general. It is something C++ programmers have to learn, but there's lots of things C++ programmers have to learn, and this isn't that much more.

    Third, provided you limit exceptions to exceptional cases, there should be minimal effects on performance. And, as Pavel Minaev has pointed out, if you have to pass error codes back with results, there's the possibility of effects on performance, since C++ isn't set up for easy returns of multiple values.

    Fourth, it is indeed difficult to make older code exception-safe. However, this is a new project.

    So, I see no good reasons not to throw exceptions in exceptional circumstances, and plenty of reasons to do so.

提交回复
热议问题