Main Content

AUTOSAR C++14 Rule A15-4-1

Dynamic exception-specification shall not be used

Since R2021a

Description

Rule Definition

Dynamic exception-specification shall not be used.

Rationale

Dynamic exception specification is the method of specifying how a function behaves in case of an exception by using a throw(<list of exceptions>) statement in the function declaration. Using dynamic exception specification has these issues:

  • Performance cost: Because dynamic exception specifications are checked at runtime, it adds to overhead and might reduce code performance.

  • Not suitable for generic programming: Because the precise type of exceptions raised by function or class templates are generally not known beforehand, it can be difficult to use throw statements in generic code.

For these reasons, avoid the throw(<list of exceptions>) statement to specify exceptions. Use the noexcept keyword instead. Because the noexcept statements are checked at compile time, it is suitable for generic programming and generally provides better performance than throw statements. The C++11 standard specifies that dynamic exception specification will be removed from C++ in the future.

Polyspace Implementation

When a throw(<list of exceptions>) statement is used in a function declaration, Polyspace® flags the throw statement. Polyspace does not flag throw statements that are used for raising an exception.

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 <string>
// throw for raising exception is compliant
void F9 () throw(std::runtime_error) {   //Non-compliant
	throw (std::runtime_error("foo"));   //Compliant
}
// Both declaration and definition is flagged
void F11 () throw(std::runtime_error);   //Noncompliant
void F11 () throw(std::runtime_error) {} //Noncompliant
// Instantiated and Noninstantiated templates are flagged
template <class T>
void F10 () throw(std::runtime_error) {  //Noncompliant
	throw (std::runtime_error("foo"));   //Compliant
}

template <class T>
void F12 () throw(std::runtime_error);   //Noncompliant
template <class T>
void foo() noexcept(noexcept(T())) {}//Compliant

void bar () {
	foo<int>();  // noexcept(noexcept(int())) => noexcept(true)
	F10<std::string> ();                 //Compliant
	
}

Polyspace flags statements such as throw(std::runtime_error) that are used in the function declarations and definitions as dynamic exception specification. Avoid dynamic exception specification. Use the keyword noexcept instead. The template foo uses the noexcept keyword as the exception specification, which is compliant with this rule.

Check Information

Group: Exception handling
Category: Required, Automated

Version History

Introduced in R2021a