How does C ++ handle assignments in catch catch blocks?

I use the clang analyzer to check C ++ code for errors and errors. I have the following construct:

#include <cstdlib> #include <iostream> double somethingThatMayThrow() throw (std::exception) { if( rand() % 2 ) { throw std::exception(); } return 5.0; } int main() { double value = 2.0; try { value = somethingThatMayThrow(); } catch( const std::exception& ) { std::cout << "oops" << std::endl; } double someOtherValue = value + 1.0; std::cout << someOtherValue << std::endl; return 0; } 

The analyzer now complains that the initial value of the value variable is never read. However, it is clear that the value is used in the last line if and only if there is an exception in the try block. Is this understanding correct and am I looking at an error in the analyzer? Or am I missing something?

How does the standard define this behavior? What happens to the left side of the job if the right side is selected?

The screenshot below shows the actual code complained of by the analyzer, which has the same structure as my example above:

clang parser detects dead storage in try catch block

+4
source share
2 answers

The analyzer is erroneous. You're right.

The analyzer may be right if the code inside the try block can never throw out std::exception or objects of a type derived from it (for example, using noexcept or only noexcept only objects of other types).

In any case, your interpretation is correct: assignment will never happen if you evaluate the values ​​to be selected. Thus, the original value will remain unchanged.

+4
source

The compiler sees that you assign someValue in the value initialization, but then inside the try block you reassign it.

And the analyzer is right in the case when the exception is not thrown, but not in the opposite case, where the value will still match the original someValue .

0
source

All Articles