I've heard and read many times that it is better to catch an exception as reference-to-const rather than as reference. Why is:
try { // stuff } catch (const std::exception& e) { // stuff }
better than:
try { // stuff } catch (std::exception& e) { // stuff }
An exception should be caught by reference rather than by value. The analyzer detected a potential error that has to do with catching an exception by value. It is much better and safer to catch exceptions by reference.
To be more specific, if you caught std::exception by reference and you just simply use throw; , you will still rethrow the original SpecialException , while if you throw e , that SpecialException will be copied into std::exception so we lose information pretty much the same way as we lost information in the case of ...
Pass Using Const Reference in C++ Now, we can use the const reference when we do not want any memory waste and do not change the variable's value. The above code will throw a compile error as num = num +10 is passed as a const reference.
You should always list catched exceptions. They are predicted. If you want to catch unpredicted exceptions and handle them the same way, you should catch RuntimeException instead.
You need:
The latter is not as much important as the former, but the only real reason to drop const would be to signal that you want to do changes to the exception (usually useful only if you want to rethrow it with added context into a higher level).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With