☰
  • 首页
  • 规则分类
  • 项目介绍
search
•••

不应捕获过于宽泛的异常

7.4 ID_catch_generic
目录 › next › previous

捕获过于宽泛的异常,如捕获 std::exception、std::logic_error、std::runtime_error 等类型的异常,或使用 catch(...) 子句捕获所有异常,会使异常处理失去针对性,而且很可能会将本不应处理的异常一并捕获。

示例:

class WrongArg {};

void foo(int a) try
{
    if (a < 0) {
        throw WrongArg();
    }
    bar(a);   // Other exceptions may be thrown
}
catch (...)   // Non-compliant
{
    std::cout << "wrong argument\n";
}

例中 foo 函数在参数不符合要求时抛出异常,bar 函数会抛出其他异常,用 catch(...) 子句将所有异常都当作“参数不符合要求”是不合理的。

例外:

try
{
    ext_interface();   // External interface
}
catch (std::exception& e)   // Let it go, but comments are required
{
    log(e.what());
}
catch (...)   // Let it go, but comments are required
{
    log("unknown exception");
}

当不受控制的外部代码会抛出未知的异常时,可酌情捕获宽泛类型的异常,但应配以文档说明问题。

相关

ID_throwGenericException

参考

CWE-396
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.