rspec/rules/S2221/csharp/rule.adoc

70 lines
1.4 KiB
Plaintext
Raw Normal View History

2023-01-11 16:18:58 +01:00
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.
2020-06-30 12:48:07 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:48:07 +02:00
----
try
{
// do something that might throw a FileNotFoundException or IOException
}
catch (Exception e) // Noncompliant
{
// log exception ...
}
----
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,csharp]
2020-06-30 12:48:07 +02:00
----
try
{
// do something
}
catch (Exception e) when (e is FileNotFoundException || e is IOException)
{
// do something
}
----
== Exceptions
2023-01-11 16:18:58 +01:00
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.
2021-02-02 15:02:10 +01:00
2023-01-11 16:18:58 +01:00
[source,csharp]
2020-06-30 12:48:07 +02:00
----
try
{
// do something
}
catch (Exception e)
{
if (e is FileNotFoundException || e is IOException)
{
// do something
}
else
{
throw;
}
}
----
include::../see.adoc[]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]