-2

Please I would like someone to explain to me the term and how to "throw by value and catch my reference". Someone said it to me, I am still a new programmer and I don't seem to understand yet.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294

2 Answers2

3

"throw by value" means to not throw (raw) pointers.

When a pointer is thrown there is a good chance of double delete (which is UB) or no delete (leaking memory), because how can a handler know whether it's supposed to delete or not?

"catch by reference" means to catch by reference, preferably reference to const. That way you avoid slicing the exception object. For example, a handler can then simply use dynamic_cast to determine if a std::exception is really a std::system_error.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
2

Well catch by reference is

...}catch(myException &me){ }

So when you say catch(myException me) , it creates a new object, but in case of reference it does not.
Additionally exceptions as references in catch blocks means polymorphic behavior is possible when accessing the object to handle the exception.

This is really helpful if the exception is off derived type. Click Me For More Info

Community
  • 1
  • 1
pratim_b
  • 1,160
  • 10
  • 29
  • I take it "throw by value" means "there's no need to say `new`, i.e., `throw std::runtime_error("message")` instead of `throw new std::runtime_error("message")` – Max Lybbert Dec 09 '13 at 07:16