Want to "throw" an exception, but are not in the HANDLER for that exception anymore.
[Enter feedback here]
Hi, what if you want to preserve the callstack, BUT you are not in the handler anymore (you saved off the exception and want to throw it later)?
Document Details
⚠ Do not edit this section. It is required for learn.microsoft.com ➟ GitHub issue linking.
- ID: 65b444d4-49e0-6d5a-ef71-1235478066b5
- Version Independent ID: 13c37e4f-453b-3578-1a3a-de6a890da280
- Content: CA2200: Rethrow to preserve stack details (code analysis) - .NET
- Content Source: docs/fundamentals/code-analysis/quality-rules/ca2200.md
- Product: dotnet-fundamentals
- GitHub Login: @gewarren
- Microsoft Alias: gewarren
I'm not certain that the code analysis description would be the correct place to document this, but it really should be documented somewhere (but isn't right now), and linking to it from this code analysis as a form of "see also" hint would be sensible.
In the interim, if you want to capture an exception for possibly rethrowing later, with a preserved callstack, you should save an ExceptionDispatchInfo object created like var edi = ExceptionDispatchInfo.Capture(ex);.
You can then later rethrow the exception with intact stack trace by calling edi.Throw(), which will rethrow the exception while preserving the stack trace, and other dispatching details. You can also inspect the exception so captured via: edi.SourceException.
This really should be documented somewhere other than documentation for the ExceptionDispatchInfo class, since for example, developers creating a custom awaitable will likely want to use it.
Perhaps use of ExceptionDispatchInfo should be mentioned here? https://learn.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap#exceptions cc @AaronRobinsonMSFT
@gewarren The suggestion from @KevinCathcart is correct.
Perhaps use of ExceptionDispatchInfo should be mentioned here?
I'm not sure adding it to the task patterns is appropriate. I agree we should add it somewhere, but I'm not sure where. The task model has different ways of handling exceptions and I'd like to avoid of confusing those two scenarios. Is there a best-practices for general Exception usage?
@AaronRobinsonMSFT Yes, we have best practice for exceptions here: https://learn.microsoft.com/en-us/dotnet/standard/exceptions/best-practices-for-exceptions. I'll add something there, thanks.