Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Consequently if two handlers catch exceptions that are derived from the same base class (such as std::exception), the most derived exception must come first.

Noncompliant Code Example

In this noncompliant code example, the first handler will catch all exceptions of class B, as well as exceptions of class D, since they are also of class B. Consequently, the second handler will not catch any exceptions.

Code Block
bgColor#FFcccc
langcpp
// Classes used for exception handling.
class B {};
class D : public B {};

void f() {
  try {
    // ...
  } catch (B &b) {
    // ...
  } catch (D &d) {
    // ...
  }
}

Compliant Solution

In this compliant solution, the first handler will catch all exceptions of class D, and the second handler will catch all the other exceptions of class B.

Code Block
bgColor#ccccff
langcpp
// Classes used for exception handling.
class B {};
class D : public B {};

void f() {
  try {
    // ...
  } catch (D &d) {
    // ...
  } catch (B &b) {
    // ...
  }
}

Risk Assessment

Exception handlers with inverted priorities cause unexpected control flow when an exception occurs of the derived type.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

ERR36-CPP

Medium

Likely

Low

P18

L1

Automated Detection

Tool

Version

Checker

Description

ECLAIR

Include Page
ECLAIR_V
ECLAIR_V

CP1.ERR36

Fully implemented

PRQA QA-C++
Include Page
PRQA QA-C++_V
PRQA QA-C++_V
4040,4034 

Related Vulnerabilities

Search for other vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

[MISRA 08]

Rule 15-3-6, "Where multiple handlers are provided in a single try-catch statement or function-try-block for a derived class and some or all of its bases, the handlers shall be ordered most-derived to base class."
Rule 15-3-7, "Where multiple handlers are provided in a single try-catch statement or function-try-block, any ellipsis (catch-all) handler shall occur last." 

Bibliography

[ISO/IEC 14882-2014]15.3, "Handling an Exception"

...