Main Content

Declaration of catch for generic exception

A catch block handles a generic exception that might have many different subtypes

Since R2022a

Description

This defect occurs when you design catch blocks to handle generic high level exceptions. Polyspace® checks the exception specifications of a function and raises a violation if a catch block handles:

  • All exceptions by using a catch-all block.

  • Exception of the class std::exception. Because std::exception is the base class for all standard C++ exceptions, a catch block that handles std::exception type matches all derived exceptions.

Risk

Using generic catch blocks hides the emergence of unexpected new exceptions and hinders their proper handling. Such generic catch blocks makes the code vulnerable to security issues. For instance:

void foo(void){
	try{
		//..
	}catch(std::exception& e){
		//Log error
	}
}
Because the catch block handles the generic std::exception class, this code hides unexpected exceptions or those that need to be handled differently. For instance, If an unexpected std::invalid_argument exception is raised in foo(), it might remain undetected by the developer because it is matched with the catch block. Because the catch block is not programmed to handle std::invalid_argument properly, the poorly handled exception becomes a vulnerability for the code.

Fix

To fix this defect, avoid catching high-level generic exceptions. Write catch blocks that handle specific exceptions to enable handling different exceptions in different ways. Unexpected or new exceptions are also easily detected when catch blocks are specific.

Examples

expand all

#include<string>
#include<exception>
#include<stdexcept>

extern void logger(std::string s, std::exception& e);
void foo(void){
	try{
		//..
	}catch(std::exception& e){ 
		 logger("foo failed", e);
	}
}

In this example, Polyspace flags the use of the generic catch block.

Correction — Use Specific Catch Blocks

To resolve this defect, use specific catch blocks. When you use specific catch blocks, new and unexpected exceptions become unhandled exceptions that are easily detected.

#include<string>
#include<exception>
extern void logger(std::string s, std::exception& e);
void foo(void){
	try{
		//..
	}catch(std::domain_error& e){ 
		 logger("Domain Error in foo", e);
	}catch(std::invalid_argument& e){
		logger("Invalid Argument in foo", e);
	}
}

Result Information

Group: Good practice
Language: C++
Default: Off
Command-Line Syntax: CATCH_FOR_GENERIC_EXCEPTION
Impact: Low

Version History

Introduced in R2022a