== Why is this an issue?

Catching an exception class by value rather than by reference can cause several problems:

* Memory is allocated unnecessarily: catching by value creates a copy of the exception object, which is destroyed at the exit of the catch block.

* Slicing occurs: the copy will be an instance of the exception base class rather than the potentially more specific exception class initially caught. So it may lead to a loss of precision as any additional data or functionality offered by the subclass will not be accessible.

* Copying the exception class may throw an exception, leading to unexpected behavior.


== How to fix it

This rule raises an issue when an exception is caught by value instead of by reference.

It is also best to avoid catching an exception by pointer (implying throwing by pointer) because it means the catch clause must manage the memory held by the pointer. The rule S1035 detects this situation.

=== Code examples

==== Noncompliant code example

[source,cpp,diff-id=1,diff-type=noncompliant]
----
try {
  // ...
} catch (ExceptionClass ex) { // Noncompliant
  //...
}
----


==== Compliant solution

[source,cpp,diff-id=1,diff-type=compliant]
----
try {
  // ...
} catch (ExceptionClass &ex) {
  //...
}
----


== Resources

=== Standards
* CERT - https://wiki.sei.cmu.edu/confluence/x/SXs-BQ[ERR61-CPP. Catch exceptions by lvalue reference]

=== External coding guidelines
* {cpp} Core Guidelines - https://github.com/isocpp/CppCoreGuidelines/blob/e49158a/CppCoreGuidelines.md#e15-throw-by-value-catch-exceptions-from-a-hierarchy-by-reference[E.15: Throw by value, catch exceptions from a hierarchy by reference]
* MISRA {cpp}:2008, 15-3-5 - A class type exception shall always be caught by reference

=== Related rules
* S1035 - An exception object should not have a pointer type

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Catch the exception by reference.


endif::env-github,rspecator-view[]
