From a8ad1fa50ff1111884f305eb5b7648eee776c2aa Mon Sep 17 00:00:00 2001 From: Vladimir Pecanac Date: Sun, 23 Aug 2026 23:39:24 +0200 Subject: [PATCH] ThrowVsThrowEx: retarget net10.0, add ExceptionDispatchInfo rethrow sample Retargets the sample from net6.0 to net10.0 and adds a fourth NUnit test showing how to rethrow a captured exception from outside the catch block with ExceptionDispatchInfo, preserving the original stack trace. --- .../ThrowVsThrowEx/ThrowVsThrowEx.csproj | 2 +- .../ThrowVsThrowEx/ThrowVsThrowExSamples.cs | 35 ++++++++++++++++++- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/exception-handling/ThrowVsThrowEx/ThrowVsThrowEx/ThrowVsThrowEx.csproj b/exception-handling/ThrowVsThrowEx/ThrowVsThrowEx/ThrowVsThrowEx.csproj index c041c2184a..52e343cb2a 100644 --- a/exception-handling/ThrowVsThrowEx/ThrowVsThrowEx/ThrowVsThrowEx.csproj +++ b/exception-handling/ThrowVsThrowEx/ThrowVsThrowEx/ThrowVsThrowEx.csproj @@ -1,7 +1,7 @@ - net6.0 + net10.0 enable None false diff --git a/exception-handling/ThrowVsThrowEx/ThrowVsThrowEx/ThrowVsThrowExSamples.cs b/exception-handling/ThrowVsThrowEx/ThrowVsThrowEx/ThrowVsThrowExSamples.cs index cd06709d9b..5ee98b8c17 100644 --- a/exception-handling/ThrowVsThrowEx/ThrowVsThrowEx/ThrowVsThrowExSamples.cs +++ b/exception-handling/ThrowVsThrowEx/ThrowVsThrowEx/ThrowVsThrowExSamples.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Diagnostics.Metrics; using System.Linq; +using System.Runtime.ExceptionServices; using System.Threading.Channels; using NUnit.Framework; @@ -74,5 +75,37 @@ at ThrowVsThrowEx.ThrowVsThrowExSamples.WrapAndThrowNewEx_KeepsTheStackTraceInTh ex.ToString()); } } + + [Test] + public void ExceptionDispatchInfo_RethrowsOutsideTheCatchBlock_KeepsTheOriginalStackTrace() + { + ExceptionDispatchInfo? captured = null; + + try + { + new ThirdPartyComponent().DoInternalWork(); + } + catch (Exception ex) + { + captured = ExceptionDispatchInfo.Capture(ex); + } + + try + { + captured?.Throw(); + } + catch (Exception ex) + { + Assert.AreEqual( + @"System.InvalidOperationException: That's a nasty bug! + at ThrowVsThrowEx.ThirdPartyComponent.g__DoDangerousOperation|1_0() + at ThrowVsThrowEx.ThirdPartyComponent.GoDeeper() + at ThrowVsThrowEx.ThirdPartyComponent.DoInternalWork() + at ThrowVsThrowEx.ThrowVsThrowExSamples.ExceptionDispatchInfo_RethrowsOutsideTheCatchBlock_KeepsTheOriginalStackTrace() +--- End of stack trace from previous location --- + at ThrowVsThrowEx.ThrowVsThrowExSamples.ExceptionDispatchInfo_RethrowsOutsideTheCatchBlock_KeepsTheOriginalStackTrace()", + ex.ToString()); + } + } } -} \ No newline at end of file +}