Main Content

Exception handler hidden by previous handler

catch statement is not reached because of an earlier catch statement for the same exception

Description

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

Examples

expand all

#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) {
        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());
    }
}

Result Information

Group: C++ Exception
Language: C++
Default: On for handwritten code, off for generated code
Command-Line Syntax: EXCP_HANDLER_HIDDEN
Impact: Medium

Version History

Introduced in R2015b