About catching exception good practices

浪尽此生 提交于 2019-12-03 06:09:17

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).

I suppose that exception should be caught in usual manner by lvalue-reference. Here's good explanation of rvalues-references use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!