メインコンテンツ

MISRA C++:2023 Rule 18.3.2

An exception of class type shall be caught by const reference or reference

R2024b 以降

説明

ルール定義

An exception of class type shall be caught by const reference or reference 1 .

根拠

クラス型の例外が値によってキャッチされると、例外オブジェクトがスライスされる可能性があります。次に例を示します。

class baseException(); 
class derivedException : public baseException {}; 

void foo() { 
	try { 
		//... 
		throw derivedException(); 
	} 
	catch (baseException e) { //slices the thrown exception 
		//... 
	} 
} 
foo() 内の catch ブロックで derivedException オブジェクトがキャッチされる場合、そのオブジェクトは derivedException オブジェクトの状態に維持されると想定されます。このオブジェクトは値によってキャッチされるため、baseException オブジェクトにスライスされます。想定外のオブジェクトのスライスは、実行時に予期しないコードの動作につながるリスクがあります。オブジェクトのスライスを回避するには、参照または const 参照によってクラス型の例外をキャッチします。

Polyspace 実装

Polyspace® は、クラス型の例外を値によってキャッチする catch ステートメントにフラグを設定します。

トラブルシューティング

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

すべて展開する

#include <exception> 
#include <iostream> 

class baseException : public std::exception { 
public: 
	baseException() : exception() {} 
	const char* what() const noexcept(true) override { 
		return "Base Exception Object"; 
	} 
}; 

class derivedException : public baseException { 
public: 
	derivedException() : baseException() {} 
	const char* what() const noexcept(true) override { 
		return "Derived Exception Object"; 
	} 
}; 

class exampleException{}; 

void foo() { 
	try { 
		throw derivedException(); 
	} 
	catch (baseException e) { //Noncompliant 
		std::cout << e.what(); 
	} 
	catch (derivedException e) { //Noncompliant 
		std::cout << e.what(); 
	} 
	catch (exampleException e) { //Noncompliant 
	} 
	catch (baseException &e) { //Compliant 
		std::cout << e.what(); 
	} 
	catch (const baseException &e) { //Compliant 
		std::cout << e.what(); 
	} 
	catch (derivedException &e) { //Compliant 
		std::cout << e.what(); 
	} 
	catch (const derivedException &e) { //Compliant 
		std::cout << e.what(); 
	} 
} 

この例では、Polyspace は例外オブジェクトを値によってキャッチする catch ブロックにフラグを設定します。次に例を示します。

  • 型の例外の catch ブロック baseExceptionderivedException、および exampleException は、スローされたクラス型の例外を値によってキャッチするため、ルールに準拠していません。これらのブロックは、例外オブジェクトをスライスする可能性があります。

  • 型の例外の catch ブロック baseException &const baseException &derivedException &、および const derivedException & は、クラス型の例外を参照または const 参照によってキャッチするため、ルールに準拠しています。

チェック情報

グループ: Exception Handling
カテゴリ: Required

バージョン履歴

R2024b で導入


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.