Main Content

MISRA C++:2008 Rule 15-1-2

NULL shall not be thrown explicitly

Description

Rule Definition

NULL shall not be thrown explicitly.

Rationale

The macro NULL is commonly used to refer to null pointers. Compliers interpret NULL as an integer with value zero, instead of a pointer. When you use NULL explicitly in a throw statement, you might expect the statement to raise a pointer type exception. The throw(NULL) is equivalent to throw(0) and raises an integer exception. This behavior might be contrary to developer expectation and might result in bugs that are difficult to find. Avoid using NULL explicitly in a throw statement.

Polyspace Implementation

Polyspace® flags a throw statement that raises a NULL explicitly. Polyspace does not flag the statement when NULL is raised after casting to a specific type or assigning it to a pointer type.

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

typedef          char         char_t;
typedef signed   int          int32_t;

#include <cstddef>

void foo()
{
	try {
		char_t * p1 = NULL;		
		throw ( NULL );            // Noncompliant
		throw(p1); //Compliant
		throw ( static_cast < const char_t * > ( NULL ) ); // Compliant
	} catch ( int32_t i ) {        // NULL exception handled here
		// /*...*/
	} catch ( const char_t * ) { // Other two exceptions are handled here
		// /*...*/
	}
}

In this example, three exceptions are raised directly by using throw statements.

  • Polyspace flags the statement throw(NULL) because it explicitly raises NULL as exception. You might expect that this statement raises a pointer type exception that is handled in the second catch block. This statement actually raises an int exception that is handled in the first catch block.

  • The other throw statements show the compliant method of using NULL in a throw statement. For instance, the second throw statement raises a char* that is assigned the value NULL. The third throw statement raises a char* by casting NULL to a char*. Because these statements do not raise NULL explicitly, Polyspace does not flag them.

Check Information

Group: Exception Handling
Category: Required

Version History

Introduced in R2013b