Main Content

AUTOSAR C++14 Rule A15-1-2

An exception object shall not be a pointer

Description

Rule Definition

An exception object shall not be a pointer.

Rationale

If your throw expression is a pointer to a dynamically allocated object, the deallocation point of the allocated resource becomes ambiguous. Such ambiguity might lead to a memory leak. Throwing pointers as exceptions might allow functions to access objects after their lifetime ends, which results in an undefined behavior.

Avoid using pointers as exceptions. Raise exceptions by copy instead.

Polyspace Implementation

The checker raises a violation if a throw statement throws an exception of pointer type.

The checker does not raise a violation if a NULL pointer is thrown as exception. Throwing a NULL pointer is forbidden according to AUTOSAR C++14 Rule M15-1-2.

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

extern int flag;
class A{/**/};
void foo(void){
	A a;
	A* a_pointer = new A;
	A& a_ref = a;
	if(flag==0){
		throw a;
	}
	
	else if(flag==2){
		throw a_pointer;//Noncompliant
	}
	
	else if(flag==-1){
		throw a_ref;
	}
	else if(flag==-2){
		throw &a; //Noncompliant
	}
}

In this example, the function foo() throws several exceptions. Polyspace flags the throw statements where the throw operand is a pointer. Raising exceptions by copy or by reference is compliant with this rule.

Check Information

Group: Exception Handling
Category: Required, Automated

Version History

Introduced in R2019a