S2221 — "Exception" should not be caught

Language
C#
Type
Code smell
Severity
Minor
Tags
cwe, error-handling

Why is this an issue?

Catching System.Exception seems like an efficient way to handle multiple possible exceptions. Unfortunately, it traps all exception types, including the ones that were not intended to be caught. To prevent any misunderstandings, exception filters should be used. Alternatively, each exception type should be in a separate catch block.

Noncompliant code example


try
{
  // do something that might throw a FileNotFoundException or IOException
}
catch (Exception e) // Noncompliant
{
  // log exception ...
}

Compliant solution


try
{
  // do something
}
catch (Exception e) when (e is FileNotFoundException or IOException)
{
  // do something
}

Exceptions

The final option is to catch System.Exception and throw it in the last statement in the catch block. This is the least-preferred option, as it is an old-style code, which also suffers from performance penalties compared to exception filters.


try
{
  // do something
}
catch (Exception e)
{
  if (e is FileNotFoundException or IOException)
  {
    // do something
  }
  else
  {
    throw;
  }
}

Resources

↑ Back to top