C++ catch blocks - catch exception by value or reference?

C++Exception Handling

C++ Problem Overview


> Possible Duplicate:
> catch exception by pointer in C++

I always catch exceptions by value. e.g

try{
...
}
catch(CustomException e){
...
}

But I came across some code that instead had catch(CustomException &e) instead. Is this a)fine b)wrong c)a grey area?

C++ Solutions


Solution 1 - C++

The standard practice for exceptions in C++ is ...

> Throw by value, catch by reference

Catching by value is problematic in the face of inheritance hierarchies. Suppose for your example that there is another type MyException which inherits from CustomException and overrides items like an error code. If a MyException type was thrown your catch block would cause it to be converted to a CustomException instance which would cause the error code to change.

Solution 2 - C++

Catching by value will slice the exception object if the exception is of a derived type to the type which you catch.

This may or may not matter for the logic in your catch block, but there is little reason not to catch by const reference.

Note that if you throw; without a parameter in a catch block, the original exception is rethrown whether or not you caught a sliced copy or a reference to the exception object.

Solution 3 - C++

Unless you want to fiddle with the exception, you should usually use a const reference: catch (const CustomException& e) { ... }. The compiler deals with the thrown object's lifetime.

Solution 4 - C++

in (CustomException e) new object of CustomException is created... so it's constructor will be called while in (CustomException &e) it will just the reference... not new object is created and no constructor will be called... so formal is little bit overhead... later is better to use...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMr. BoyView Question on Stackoverflow
Solution 1 - C++JaredParView Answer on Stackoverflow
Solution 2 - C++CB BaileyView Answer on Stackoverflow
Solution 3 - C++Marcelo CantosView Answer on Stackoverflow
Solution 4 - C++Mihir MehtaView Answer on Stackoverflow