TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
C++ Coding Standard
Search

Rule:  ERR54-CPPChecked automatically with code checker

Synopsis:Catch handlers should order their parameter types from most derived to least derived
Language:C++
Severity Level:1
Category:Security


Description:

The C++ Standard, [except.handle], paragraph 4 [ISO/IEC 14882-2014], states the following:

The handlers for a try block are tried in order of appearance. That makes it possible to write handlers that can never be executed, for example by placing a handler for a derived class after a handler for a corresponding base class.

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 catches all exceptions of class B , as well as exceptions of class D , since they are also of class B . Consequently, the second handler does not catch any exceptions.

// 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 catches all exceptions of class D , and the second handler catches all the other exceptions of class B .

// Classes used for exception handling
class B {};
class D : public B {};
 
void f() {
   try {
     // ...
   } catch (D &d) {
     // ...
   } catch (B &b) {
     // ...
   }
}