重新抛出异常变量¶
ID: cs/rethrown-exception-variable
Kind: problem
Security severity:
Severity: warning
Precision: very-high
Tags:
- maintainability
- language-features
- exceptions
Query suites:
- csharp-security-and-quality.qls
重新抛出异常变量将丢失原始异常中的堆栈跟踪,并将其替换为 throw
语句中的堆栈跟踪。这将使调试异常的根本原因变得更加困难,例如,如果堆栈跟踪被写入日志文件。
建议¶
考虑使用 throw;
重新抛出原始异常。这不仅更简单,而且还将保留原始堆栈信息。
示例¶
此示例显示了一个异常处理程序,如果抛出异常,它会将状态设置为 UnexpectedException
。但是,它会抛出 ex
,这会丢弃包含错误源的原始堆栈跟踪。
try
{
Run();
status = Status.Success;
}
catch (Exception ex)
{
status = Status.UnexpectedException;
throw ex; // BAD
}
修复方法是按如下方式替换 throw
语句
try
{
Run();
status = Status.Success;
}
catch
{
status = Status.UnexpectedException;
throw; // GOOD
}
由于不再需要变量 ex
,因此已删除 catch 变量。
参考¶
MSDN:创建和抛出异常(C# 编程指南)。
MSDN:throw(C# 参考)。