CodeQL documentation

Catching by value

ID: cpp/catch-by-value
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - efficiency
   - correctness
   - exceptions
Query suites:
   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

Catching an exception by value will create a new local variable which is a copy of the originally thrown object. Creating the copy is slightly wasteful, but not catastrophic. More worrisome is the fact that if the type being caught is a strict supertype of the originally thrown type, then the copy might not contain as much information as the original exception.

Recommendation

The parameter to the catch block should have its type changed from T to T& or const T&.

Example

void bad() {
  try {
    /* ... */
  }
  catch(std::exception a_copy_of_the_thrown_exception) {
    // Do something with a_copy_of_the_thrown_exception
  }
}

void good() {
  try {
    /* ... */
  }
  catch(const std::exception& the_thrown_exception) {
    // Do something with the_thrown_exception
  }
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy