Details
-
Type:
Code Smell Detection
-
Status: Active
-
Resolution: Unresolved
-
Labels:
-
Message:Catch a type that inherit from "std::exception".
-
Highlighting:
-
Default Severity:Major
-
Impact:Low
-
Likelihood:High
-
Covered Languages:C, C++
-
Remediation Function:Constant/Issue
-
Constant Cost:20min
-
Analysis Scope:Main Sources, Test Sources
-
CppCoreGuidelines:E.14
Description
Throwing as an exception an object that is not derived from std::exception is a bad practice. It is usually unreliable, meaningless, and a source of type clashes.
For the same reason, catching a non-exception type is a sign that your application has a bad exception-handling design. You should use standard exception types or create your own exception types that inherit at some level from std::exception.
Noncompliant Code Example
try { /* code that can throw: 42 */ } catch (int ex) { // Noncompliant if (ex == 42) { /*...*/ } }
Compliant Solution
try { /* code that can throw: std::domain_error("User ID not found.") */ } catch (const std::domain_error& ex) { /*...*/ }
See
- C++ Core Guidelines E.14 - Use purpose-designed user-defined types as exceptions (not built-in types)