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

不应抛出过于宽泛的异常

7.3 ID_throwGenericException
目录 › next › previous

抛出过于宽泛的异常,如 std::exception、std::logic_error、std::runtime_error 等类型的异常,会使异常处理失去针对性,而且处理这种异常时很可能会将本不应处理的异常一并捕获。

示例:

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

foo 函数在参数不符合要求时抛出 std::exception 类的异常,过于宽泛,如果 bar 函数抛出从 std::exception 派生的其他异常,也会被当作“参数不符合要求”处理。

应为异常定义具体的类:

class WrongArg {};

void foo(int a) try
{
    if (a < 0) {
        throw WrongArg();   // Compliant
    }
    bar(a);
}
catch (WrongArg&)   // Right
{
    std::cout << "wrong argument\n";
}

相关

ID_catch_generic

参考

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