メインコンテンツ

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.

説明

ルール定義

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. 1

根拠

try-catch または function-try ブロックでは、派生クラスの例外オブジェクトが、基底クラスを受け入れるハンドラー catch ブロックに一致します。基底例外クラスのハンドラーを派生例外クラスのハンドラーの前に配置すると、基底クラス ハンドラーが基底クラス例外と派生クラス例外の両方を処理します。派生クラス ハンドラーは到達不能コードになり、予期せぬ動作となります。クラス階層を使用して例外を発生させるときは、必ず派生クラスのハンドラーが基底クラスのハンドラーに先行するようにします。

Polyspace 実装

ハンドラー ブロックが基底クラスのハンドラーより後にある場合、Polyspace® はそのハンドラー ブロックにフラグを設定します。

トラブルシューティング

ルール違反が想定されるものの、Polyspace から報告されない場合は、コーディング規約違反が想定どおりに表示されない理由の診断を参照してください。

すべて展開する

#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
	}
}

この例では、階層内の 3 つのクラスが try ブロック内に出現する可能性があります。ハンドラー catch ブロックが例外を処理します。

  • ブロック catch ( NotANumber &nan ) は、その基底クラス catch ( MathError &e ) のハンドラーの後にあります。NotANumber クラスの例外もハンドラー catch ( MathError &e ) に一致するため、ハンドラー ブロック catch ( NotANumber &nan ) が到達不能コードになります。このブロックの順序はこのルールに準拠していません。Polyspace は、このハンドラー ブロックにフラグを設定します。

  • ブロック catch ( DivideByZero &dbz ) は到達不能コードになります。DivideByZero クラスの例外が、先行する基底クラスのハンドラーに一致するためです。Polyspace は、ハンドラー ブロック catch ( DivideByZero &dbz ) にフラグを設定します。

チェック情報

グループ: Exception Handling
カテゴリ: 必要

バージョン履歴

R2013b で導入


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.