Modify S2221: Improve compliant example (#3946)

This commit is contained in:
Sebastien Marichal 2024-05-24 11:02:24 +02:00 committed by GitHub
parent e98c6d6b3f
commit 0ef2f90ef5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,6 +1,6 @@
== 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, the exception filters should be used. Alternatively each exception type should be in a separate `catch` block.
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
@ -24,7 +24,7 @@ try
{
// do something
}
catch (Exception e) when (e is FileNotFoundException || e is IOException)
catch (Exception e) when (e is FileNotFoundException or IOException)
{
// do something
}
@ -32,7 +32,7 @@ catch (Exception e) when (e is FileNotFoundException || e is IOException)
=== 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 penalty compared to exception filters.
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.
[source,csharp]
----
@ -42,7 +42,7 @@ try
}
catch (Exception e)
{
if (e is FileNotFoundException || e is IOException)
if (e is FileNotFoundException or IOException)
{
// do something
}