Main Content

CWE Rule 755

Improper Handling of Exceptional Conditions

Since R2024a

Description

Rule Description

The product does not handle or incorrectly handles an exceptional condition.

Polyspace Implementation

The rule checker checks for Exception handler hidden by previous handler.

Examples

expand all

Issue

This issue occurs when a catch statement is not reached because a previous catch statement handles the exception.

For instance, a catch statement accepts an object of a class my_exception and a later catch statement accepts one of the following:

  • An object of the my_exception class.

  • An object of a class derived from the my_exception class.

Risk

Because the catch statement is not reached, it is effectively dead code.

Fix

One possible fix is to remove the redundant catch statement.

Another possible fix is to reverse the order of catch statements. Place the catch statement that accepts the derived class exception before the catch statement that accepts the base class exception.

Example — catch Statement Hidden by Previous Statement
#include <new>

extern void print_str(const char* p);
extern void throw_exception();

void func() {
    try {
        throw_exception();
    }
    catch(std::exception& exc) {
        print_str(exc.what());
    }

    catch(std::bad_alloc& exc) { //Noncompliant
        print_str(exc.what());
    }
}

In this example, the second catch statement accepts a std::bad_alloc object. Because the std::bad_alloc class is derived from a std::exception class, the second catch statement is hidden by the previous catch statement that accepts a std::exception object.

The defect appears on the parameter type of the catch statement. To find which catch statement hides the current catch statement:

  1. On the Source pane, right-click the keyword catch and select Search For "catch"in Current Source File.

  2. On the Search pane, click each search result, proceeding backward from the current catch statement. Continue until you find the catch statement that hides the catch statement with the defect.

Correction — Reorder catch Statement

One possible correction is to place the catch statement with the derived class parameter first.

#include <new>

extern void print_str(const char* p);
extern void throw_exception();

void corrected_excphandlerhidden() {
    try {
        throw_exception();
    }
    
    catch(std::bad_alloc& exc) {
        print_str(exc.what());
    }
    catch(std::exception& exc) {
        print_str(exc.what());
    }
}

Check Information

Category: Others

Version History

Introduced in R2024a