Sprog
Bemærk
Adgang til denne side kræver godkendelse. Du kan prøve at logge på eller ændre mapper.
Adgang til denne side kræver godkendelse. Du kan prøve at ændre mapper.
| Property | Value |
|---|---|
| Rule ID | CA2219 |
| Title | Do not raise exceptions in exception clauses |
| Category | Usage |
| Fix is breaking or non-breaking | Non-breaking, Breaking |
| Enabled by default in .NET 10 | As suggestion |
| Enabled by default in .NET 11 | As suggestion |
| Applicable languages | C# and Visual Basic |
Cause
An exception is thrown from a finally, filter, or fault clause.
Rule description
When an exception is raised in an exception clause, it greatly increases the difficulty of debugging.
When an exception is raised in a finally or fault clause, the new exception hides the active exception, if present. This masking makes the original error hard to detect and debug.
When an exception is raised in a filter clause, the runtime silently catches the exception and causes the filter to evaluate to false. There is no way to tell the difference between the filter evaluating to false and an exception being thrown from a filter. This behavior makes it hard to detect and debug errors in the filter's logic.
How to fix violations
To fix a violation of this rule, ensure that exceptions are not thrown from a finally, filter, or fault clause. Use the following patterns to handle operations that might fail during cleanup:
Handle cleanup exceptions inside finally without masking active exceptions
If cleanup operations—such as disposing unmanaged resources, closing streams, or calling native P/Invoke APIs—can fail inside a finally clause, choose between letting required cleanup failures propagate or swallowing best-effort cleanup failures:
- Required cleanup (
Run): If the caller needs to know when cleanup fails (for example, closing a buffered output stream can fail while flushing data), track whether thetryblock succeeded and catch cleanup exceptions with an exception filter (when (!primarySucceeded)). When the primary operation succeeds, any cleanup exception propagates directly from thefinallyclause with its original stack intact. When the primary operation already threw, the cleanup exception is handled insidefinallyso it doesn't mask the active exception. - Best-effort cleanup (
RunWithBestEffortCleanup): If cleanup failure doesn't affect the outcome of the operation, wrap the cleanup in atry/catchblock insidefinallyto swallow (and optionally log) the exception.
public void Run()
{
bool primarySucceeded = false;
try
{
PerformPrimaryOperation();
primarySucceeded = true;
}
finally
{
try
{
CleanupResource();
}
catch (Exception ex) when (!primarySucceeded)
{
// The primary operation already failed. Log on a best-effort basis
// and swallow the cleanup exception so it doesn't mask the original failure.
TryLogCleanupFailure(ex);
}
}
}
public void RunWithBestEffortCleanup()
{
try
{
PerformPrimaryOperation();
}
finally
{
try
{
CleanupResource();
}
catch (Exception ex)
{
// Best-effort cleanup: log without throwing so neither success nor
// an in-flight exception from PerformPrimaryOperation is affected.
TryLogCleanupFailure(ex);
}
}
}
private void TryLogCleanupFailure(Exception ex)
{
try
{
_logger.LogError(ex, "Failed to clean up resource.");
}
catch
{
// Logging is best effort. A logging failure must not replace the original exception.
}
}
Public Sub Run()
Dim primarySucceeded As Boolean = False
Try
PerformPrimaryOperation()
primarySucceeded = True
Finally
Try
CleanupResource()
Catch ex As Exception When Not primarySucceeded
' The primary operation already failed. Log on a best-effort basis
' and swallow the cleanup exception so it doesn't mask the original failure.
TryLogCleanupFailure(ex)
End Try
End Try
End Sub
Public Sub RunWithBestEffortCleanup()
Try
PerformPrimaryOperation()
Finally
Try
CleanupResource()
Catch ex As Exception
' Best-effort cleanup: log without throwing so neither success nor
' an in-flight exception from PerformPrimaryOperation is affected.
TryLogCleanupFailure(ex)
End Try
End Try
End Sub
Private Sub TryLogCleanupFailure(ex As Exception)
Try
_logger.LogError(ex, "Failed to clean up resource.")
Catch
' Logging is best effort. A logging failure must not replace the original exception.
End Try
End Sub
Logging can also throw—for example, when a logging provider fails while writing an entry. The TryLogCleanupFailure helper catches those exceptions so that a logging failure can't replace the original exception.
Avoid throwing inside exception filters
Exception filters (catch (...) when (condition)) should only execute non-throwing expressions. If an expression inside a filter throws an exception, the runtime catches it silently and evaluates the filter as false. To log exceptions during filtering, call methods that handle their own internal errors and safely return false.
Use Environment.FailFast for unrecoverable cleanup failures
If a resource failure in a finally block indicates critical corruption where the application cannot safely continue running (for example, critical state corruption in native interop), call Environment.FailFast instead of throwing a managed exception. FailFast terminates the process immediately and generates a crash report without executing further finalizers or handlers.
Example
The following example shows code that violates the rule:
try
{
// ...
}
finally
{
// This code violates the rule.
throw new Exception();
}
When to suppress warnings
Do not suppress a warning for this rule. An unhandled exception escaping from a finally block discards and overrides any active exception from the try block, obscuring the root cause of failures.
Related rules
CA1065: Do not raise exceptions in unexpected locations