Generic catch clauseΒΆ
ID: cs/catch-of-all-exceptions
Kind: problem
Security severity:
Severity: recommendation
Precision: high
Tags:
- quality
- reliability
- error-handling
- external/cwe/cwe-396
Query suites:
- csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
Catching all exceptions with a generic catch clause may be overly broad. This can make errors harder to diagnose when exceptions are caught unintentionally.
RecommendationΒΆ
If possible, catch only specific exception types to avoid catching unintended exceptions.
ExampleΒΆ
In the following example, a division by zero is incorrectly handled by catching all exceptions.
double reciprocal(double input)
{
try
{
return 1 / input;
}
catch
{
// division by zero, return 0
return 0;
}
}
In the corrected example, division by zero is correctly handled by only catching appropriate DivideByZeroException
exceptions. Moreover, arithmetic overflow is now handled separately from division by zero by explicitly catching OverflowException
exceptions.
double reciprocal(double input)
{
try
{
return 1 / input;
}
catch (DivideByZeroException)
{
return 0;
}
catch (OverflowException)
{
return double.MaxValue;
}
}
ReferencesΒΆ
Common Weakness Enumeration: CWE-396.