docs icon indicating copy to clipboard operation
docs copied to clipboard

Want to "throw" an exception, but are not in the HANDLER for that exception anymore.

Open ScotMac opened this issue 3 years ago • 4 comments

[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.


Associated WorkItem - 64036

ScotMac avatar Jan 11 '23 08:01 ScotMac

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.

KevinCathcart avatar Feb 10 '23 15:02 KevinCathcart

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 avatar Feb 14 '23 23:02 gewarren

@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 avatar Feb 15 '23 01:02 AaronRobinsonMSFT

@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.

gewarren avatar Feb 15 '23 19:02 gewarren