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.
-
3http://ptgmedia.pearsoncmg.com/images/0321113586/items/sutter_item73.pdf – Jamal Dec 09 '13 at 07:08
2 Answers
"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
.

- 142,714
- 15
- 209
- 331
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
-
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