Main Content

CWE Rule 396

Declaration of Catch for Generic Exception

Since R2023a

Description

Rule Description

Catching overly broad exceptions promotes complex error handling code that is more likely to contain security vulnerabilities.

Polyspace Implementation

The rule checker checks for Declaration of catch for generic exception.

Examples

expand all

Issue

This issue 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.

Example — Avoid Generic Catch Blocks
#include<string>
#include<exception>
#include<stdexcept>

extern void logger(std::string s, std::exception& e);
void foo(void){
	try{
		//..
	}catch(std::exception& e){  //Noncompliant
		 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);
	}
}

Check Information

Category: Error Conditions, Return Values, Status Codes

Version History

Introduced in R2023a