4 ms·
I couldn’t agree more and have long been arguing that we should use exceptions when they are a useful tool for the job because their semantics do what we need a
by Chris_Newton 14y ago
I couldn’t agree more and have long been arguing that we should use exceptions when they are a useful tool for the job because their semantics do what we need at the time. Sometimes that means exiting early because you can’t do what you’ve been asked to for some reason. Other times it means exiting early because you’ve already done everything you were asked to and there is no point in continuing further.
The main thing I would add to the original article is that the author is being a little kind to the critics on some of those points. For example, not only do exceptions not inherently need to be slow, they can actually be faster than the “classical” equivalent via return codes and the like. This is essentially because any jump-table-based exception mechanism means the non-exceptional control path can omit all the test logic that would serve only to exit the current block early. That could both reduce the size of the non-exceptional code and reduce the number of potential branches, each of which can be helpful for optimization. Although it’s rather less significant in performance terms because it only tends to happen once, when an exception does occur you also don’t have to run through all the individual levels of unwinding the stack with a jump table approach, as you can jump straight to levels that actually need to do something on their way to handling the exception and skip over anything that was just going to return immediately anyway.
As another minor data point, I haven’t found exceptions in C++ to be slow. Most/all of the major compilers seemed to have moved to a table-driven approach last time I used a broad set of them. The nasty overhead in C++ is more likely to be in the size of the generated executables; I’ve seen a compilation with exceptions disabled shave nearly 1/3 off the executable size.
Of course exceptions have somewhat different meanings and can have very different implementation overheads in different languages, so I’m not arguing that all advice to use them sparingly is bad. As always, it’s important to separate the dogma from the rational arguments.