2

Sutter and Alexandrescu's coding standards tell us to catch exceptions by reference.

Of course, blanket recommendations like this often have occasional exceptions (no pun intended). Are there any use cases where catching an exception by value should be preferred?

HighCommander4
  • 50,428
  • 24
  • 122
  • 194
  • @LeonLi No, that question is asking which is generally better. This question already states that answer as a presupposition. – Potatoswatter Jul 18 '13 at 02:50
  • 1
    What?? That q *only* talks about pointers, which this doesn't mention. This question isn't about best practice, which the others address, it's about a specific case already outside the accepted best practice. – Potatoswatter Jul 18 '13 at 03:45

1 Answers1

5

The advantage to catching a reference, besides obvious reasons of not requiring copyability or performing a copy (potentially a slicing one), is that you can modify it and continue processing with throw;.

If you want to modify the object, yet continue exception processing with throw; on the non-modified object, then you must make a copy, and one way of doing so is catch by value.

I think it's pretty contrived, though. Catch by const reference followed by an explicit copy would better express intent.

Also note, throwing a new C++11 nested_exception will nest the previously thrown exception object, not the object received by value, within the new exception. In such conditions you could conceivably keep your own reference to the received exception, which would go stale unless you received it by reference.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
  • 4
    Another reason for catching by reference is to avoid slicing when a derived exception class is thrown and then caught using a base class reference. – Remy Lebeau Jul 18 '13 at 02:50