I\'m writing a little program in C++11 and really use exceptions for one of the first time.
I\'ve got a question about how to catch the exceptions efficiently, and after
You should catch by const lvalue reference (2):
try { throw std::exception{"what"}; }
catch (const std::exception& ex) {}
Rationale:
In C++11 it is possible (via use of shared_future
) that two threads could be unwinding the same exception at the same time. This can happen in your code even if you are not aware of shared_future
being used, unless you control the entire application.
If two threads are caught unwinding the same exception simultaneously, and one or both of the threads modifies the exception, then you've got a race condition.
So as long as you don't have to modify the exception object in the catch clause, let the compiler enforce that policy for you - catch by const&
. If you really do need to modify the exception, then make a copy of it, modify the copy and throw the copy. You can do this by catching by value if you are sure this won't slice your exception object (which is not usually the case if you are catching std::exception
).