Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

4
  • 3
    Hmm, are C++ exceptions cost-free? In many other languages, exceptions are quite expensive if one gets thrown, and the accepted practice in those languages is to use some alternative (like error codes) if you can't afford the expense. Commented Aug 12, 2021 at 13:51
  • 1
    @RobertHarvey a relevant remark ondeed. Exceptions in C++ are n longer what they were in the early days. See the link in the last sentence: In principle, no noticeable overhead for trying. Of course if an exception is thrown there is a slightly more important cost than a return or a good old longjmp(). After all, the code needs to find the right catch and unwind the stack to properly destroy what has to be destroyed. This is why I insisted on the fact that it should be for exceptional cases and not for a frequently expected situation (i.e.a normal result rather than a real “error”). Commented Aug 12, 2021 at 14:16
  • 1
    I think throwing / catching an exception has some cost, but a lot of it is cost that you would have to suffer anyway. For example, if exception throwing calls destructors of intermediate objects, these destructors would or should have been called with C style error codes as well. Commented Nov 12, 2023 at 22:49
  • @gnasher729 Thanks for the very interesting argument. So not only has the try no overhead, but a part of the overhead of the throw could in fact not be a real overhead, as it corresponds to the destruction of objects that should anyhow be deleted. The overhead seems mostly related to a loss of potential optimisations in some cases as well as cash misses (the last link is to an SO question that goes quite deep on these elements) ;-) Commented Nov 12, 2023 at 23:02