Day_Dreamer
Day_Dreamer

Reputation: 3373

Catching objects by reference

I am new to C++. I saw some code examples that use catch blocks in which the exception is caught by value. For example:

catch(SomeClass e)

I've also seen some examples that catch by reference:

catch(const std:: out_of_range& e)

I assume that in case that exceptions are caught by reference, it should be by const reference.

My question is, when it is recommended to use each way, and what are the advantages/disadvanges in each way?

Thanks!

Upvotes: 1

Views: 79

Answers (2)

Mark Ransom
Mark Ransom

Reputation: 308186

I can't think of any advantage to catching by value, and it leads to the possibility of object slicing where the object is converted to the base class and information is lost. I'd catch by reference, always.

It's possible to modify the caught object and re-throw it for example, so you don't have to make it a const reference. But that's a good idea too.

Upvotes: 3

templatetypedef
templatetypedef

Reputation: 372814

It's recommended that you catch exceptions by reference for two reasons:

  1. Catching the exception by value will end up making a copy of the thrown exception object (the same way that passing a parameter will make a copy of that object). Even though exception handling can be a bit slow, it's still worth trying to avoid this inefficiency.

  2. If you throw an exception of a derived type and catch the base type by value, you will slice the exception the same way that passing a derived type into a function by value will slice that object. This can lead to incorrect or unusual behavior in the program.

Hope this helps!

Upvotes: 6

Related Questions