0 Tage Serie
csharp / expert
Snippet

Erhaltung von Exception-Stacktraces mittels ExceptionDispatchInfo

In der C#-Fehlerbehandlung setzt 'throw ex' den Stacktrace auf die aktuelle Zeile zurück. ExceptionDispatchInfo ermöglicht es, eine Exception zu erfassen und erneut zu werfen, während die ursprüngliche Quelle und der Stacktrace erhalten bleiben, was für das Debugging komplexer asynchroner oder mehrschichtiger Anwendungen entscheidend ist.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System.Runtime.ExceptionServices;
try
{
// Complex operation that might fail
ExecuteProcess();
}
catch (Exception ex)
{
// Capture exception state to avoid losing stack trace on re-throw
var dispatchInfo = ExceptionDispatchInfo.Capture(ex);
LogFailure(ex);
// Rethrows without modifying the 'StackTrace' property
dispatchInfo.Throw();
}
Erklärung
1
ExceptionDispatchInfo.Capture(ex)
Erfasst das Exception-Objekt und den aktuellen Call-Stack-Zustand in einem Container.
2
dispatchInfo.Throw()
Wirft die erfasste Exception erneut und behält dabei die ursprünglichen Stack-Informationen bei, als wäre sie nie abgefangen worden.