Main Content

MISRA C++:2008 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

Description

Rule Definition

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.

Rationale

In a try-catch or function-try block, exception objects of a derived class match to handler catch blocks that accept the base class. If you place handlers of the base exception class before handlers of the derived exception class, the base class handler handles both base and derived class exceptions. The derived class handler becomes unreachable code, which is unexpected behavior. When using a class hierarchy to raise exceptions, make sure that the handler of a derived class precedes the handler of a base class.

Polyspace Implementation

Polyspace® flags a handler block if it follows a handler of a base class.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include<exception>
// classes used for exception handling
class MathError { };
class NotANumber: public MathError { };
class DivideByZero: public NotANumber{};

void bar(void){
	try
	{
		// ...
	}
	catch ( MathError &e ) 
	{
		// ...
	}
	catch ( NotANumber &nan ) // Noncompliant
	{
		// Unreachable Code
		
	}
	catch (DivideByZero &dbz)//Noncompliant
	{
		//Unreachable Code
	}
}

In this example, three classes in a hierarchy might arise in the try block. The handler catch blocks handle the exceptions.

  • The block catch ( NotANumber &nan ) follows the handler of its base class catch ( MathError &e ). Because the exception of class NotANumber also matches to the handler catch ( MathError &e ), the handler block catch ( NotANumber &nan ) becomes unreachable code. The order of this block is noncompliant with this rule. Polyspace flags the handler block.

  • The block catch ( DivideByZero &dbz ) becomes unreachable code because exceptions of the class DivideByZero match to the preceding handlers of its base classes. Polyspace flags the handler block catch ( DivideByZero &dbz ).

Check Information

Group: Exception Handling
Category: Required

Version History

Introduced in R2013b