Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why catch an exception as reference-to-const?

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 } 
like image 935
cairol Avatar asked Jan 27 '10 07:01

cairol


People also ask

Why is it preferred to catch exceptions by reference instead of by value?

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.

Why we have to catch a exception by reference explain?

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

When should we use a const reference and why?

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.

Should you always catch exceptions?

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.


1 Answers

You need:

  • a reference so you can access the exception polymorphically
  • a const to increase performance, and tell the compiler you're not going to modify the object

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

like image 130
Kornel Kisielewicz Avatar answered Oct 03 '22 13:10

Kornel Kisielewicz