Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About catching exception good practices

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 some googling I still don't have the answer.

Here is the question : What is the more efficient (or recommended) between catching the exception by (const?) lvalue reference, or by (const?) rvalue reference?

In code this give :

1)

try { throw std::exception{"what"}; }
catch (std::exception& ex) {}

2)

try { throw std::exception{"what"}; }
catch (const std::exception& ex) {}

3)

try { throw std::exception{"what"}; }
catch (std::exception&& ex) {}

4)

try { throw std::exception{"what"}; }
catch (const std::exception&& ex) {}
like image 763
Geoffroy Avatar asked Sep 28 '11 10:09

Geoffroy


2 Answers

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

like image 135
Howard Hinnant Avatar answered Nov 19 '22 03:11

Howard Hinnant


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

like image 1
Andrey Atapin Avatar answered Nov 19 '22 01:11

Andrey Atapin