Throw by value and catch by (const) reference

ID

c.correctness.throw_by_value_catch_by_reference

Severity

low

Remediation Complexity

medium

Remediation Risk

medium

Remediation Effort

low

Resource

Error Handling

Language

C / C++

Description

Catch exceptions by (const) reference and throw them by value. Catching by value slices derived exception objects and copies them; catching or throwing a pointer (throw new …​) leaks the allocation unless every handler deletes it. Prefer catch (const Ex &e) and throw Ex(…​);.

Rationale

Catch exceptions by (const) reference and throw them by value. Catching by value slices derived exception objects and copies them; catching or throwing a pointer (throw new …​) leaks the allocation unless every handler deletes it. Prefer catch (const Ex &e) and throw Ex(…​);.

The following code illustrates the pattern detected by this rule:

void handler() {
  // FLAGGED: Throw by value and catch by (const) reference
  try { risky(); } catch (MyError e) { log(e.code); }

  // FLAGGED: Throw by value and catch by (const) reference
  try { risky(); } catch (MyError *e) { log(e->code); }

Remediation

Follow secure coding practices and review the references below for detailed remediation guidance.

Configuration

This detector does not need any configuration.