通用捕获子句¶
ID: cs/catch-of-all-exceptions
Kind: problem
Security severity:
Severity: recommendation
Precision: high
Tags:
- reliability
- maintainability
- external/cwe/cwe-396
Query suites:
- csharp-security-and-quality.qls
使用通用捕获子句捕获所有异常可能过于宽泛。这可能会导致在意外捕获异常时难以诊断错误。
建议¶
如果可能,请仅捕获特定异常类型,以避免捕获意外异常。
示例¶
在以下示例中,除以零错误通过捕获所有异常的方式进行处理,这是不正确的。
double reciprocal(double input)
{
try
{
return 1 / input;
}
catch
{
// division by zero, return 0
return 0;
}
}
在更正后的示例中,除以零错误通过仅捕获相应的 DivideByZeroException
异常来正确处理。此外,现在通过显式捕获 OverflowException
异常,将算术溢出与除以零分开处理。
double reciprocal(double input)
{
try
{
return 1 / input;
}
catch (DivideByZeroException)
{
return 0;
}
catch (OverflowException)
{
return double.MaxValue;
}
}
参考¶
常见弱点枚举:CWE-396。