== Why is this an issue?

When `throw` is followed by an expression, this expression will be used to create and initialize the exception object. In other words, the exception object is _copy-initialized_ from the expression.

[source,cpp]
----
catch (const std::exception& ex) {
  // ...
  throw ex; // "throw" copy-initializes the exception object from "ex"
}
----

Rethrowing an unmodified copy of the caught exception is a bad practice because:

* The exception already exists, so it is better to reuse it instead of creating a new one and wasting resources.
* 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.

== How to fix it

The rule raises an issue when the argument of the `throw` expression is an unmodified copy of the caught exception.

=== Code examples

==== Noncompliant code example

[source,cpp,diff-id=1,diff-type=noncompliant]
----
try {
  throw std::invalid_argument("x");
} catch (const std::exception& ex) {
  // ...
  throw ex; // Noncompliant: the received "std::invalid_argument" exception is copied into a less specialized class "std::exception"
}
----

==== Compliant solution

[source,cpp,diff-id=1,diff-type=compliant]
----
try {
  throw std::invalid_argument("x");
} catch (const std::exception& ex) {
  // ...
  throw; // Compliant: rethrows the initial "std::invalid_argument" exception
}
----

== Resources

=== Documentation

* {cpp} reference - https://en.cppreference.com/w/cpp/language/throw[`throw` expression]
* {cpp} reference - https://en.cppreference.com/w/cpp/language/copy_initialization[Copy initialization]


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

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

=== Message

Remove "XXX" from this "throw" statement to rethrow the original exception.


=== Highlighting

variable after the "throw" keyword


'''
== Comments And Links
(visible only on this page)

=== on 4 Aug 2015, 19:57:27 Ann Campbell wrote:
\[~tamas.vajk] I've mapped this to FxCop RethrowToPreserveStackDetails even though the reasoning seems to be different, the title and code samples are remarkably similar.


\[~evgeny.mandrikov] I have found only nebulous hints that the stacktrace is reset in {cpp} in this Noncompliant scenario (which is the logic behind the C# FxCop rule). Can you confirm/deny? If true, it would be a valuable addition to the description IMO.

=== on 21 Feb 2017, 15:41:02 Ann Campbell wrote:
Nice find [~alexandre.gigleux]. Mapped.

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