3 ms·
In C++, exceptions are often faster than manual error checking when errors are rare. But C++ does not provide a stack trace.
by petters 7y ago
In C++, exceptions are often faster than manual error checking when errors are rare.
But C++ does not provide a stack trace.
- safety-second 7y agoC++ exceptions are only good if you use them like signals from C or panics in Go. This means you have to use error values for 99% of errors or you lose this benefit. The fact that the STL sprinkles exceptions everywhere doesn't help this. C++ exceptions are so non-deterministic and slow that every real-time system disables them just to be sure.
- iainmerrick 7y agoYou don’t always get a stack trace, but it still has to unwind the stack, calling destructors as needed, and check the exception’s type against each catch block.
- earenndil 7y agoHence 'when errors are rare'.
- iainmerrick 7y agoI guess we’re violently agreeing? Exceptions are an order of magnitude (or several orders) slower than function calls and returns; but that can still be efficient overall, if only a tiny fraction of calls fail. I’d simply add that most people greatly underestimate how expensive exceptions are, even in C++.
- AstralStorm 7y agoCalling the destructors is identical to ending any scope in C++, including function calls. Where is that extra expense?
- iainmerrick 7y agoYou likely have to parse exception blocks and maybe chase pointers to find the objects to destroy. In the happy path, you can just call the destructors directly.
- renox 7y ago> But C++ does not provide a stack trace Which makes exception in C++ a very, very bad idea! My reaction to 'the test fails because map::at threw an exception': stupid STL!! A core dump would be so much easier to analyze.. Gdb's 'catch thow' is wonderful (well, it is after I fixed the part of our codebase which use exceptions as a control flow mechanism)
- nemetroid 7y ago> My reaction to 'the test fails because map::at threw an exception': stupid STL!! > A core dump would be so much easier to analyze.. Uncaught exceptions call terminate(), which by default calls abort(), which generates a core dump. So if you want a core dump, just avoid catching the exception.
- renox 7y agoExcept that I didn't put all these "catch".. But you're right, that's what should be done (or at least, rethrowing the exception from the catch block).
- AstralStorm 7y agoC++ can have a stack trace, there are enough libraries providing this functionality and even compiler extensions. Say, libunwind, though you will have to demangle names. And a debugger will see the stack as it is. Also works in C.