I don't do a lot of exception handling. I write code that avoids it as best as it can. The edges of my systems are out of my control. The edges of my system do throw exceptions.
If I can't do the correct thing for the exception, I bubble the exception up and it's gonna take down my app.
Or... more likely, I have a handler at the top to deal with it gracefully. If I can't fix it at the point the exception is coming in, I probably can't fix it anywhere so I should just let things explode.
How to re-throw. Well... you can use throw
. Sure.
At Seattle Code Camp (2018 or 2019 since those are the only years I attended) I saw a presentation that talked in depth about exception handling.
I'm pretty sure it was Ted Neward that gave the talk.. I'm giving him credit for it anyway. :)
The presentation got me thinking very deeply about exceptions and their behavior. I played with exception behaviors for many hours after the talk. The one thing I recall from the talk is the best way to preserve stack information when rethrowing an exception
ExceptionDispatchInfo.Capture(ex).Throw();
You might need to add a throw
after it for the compiler to be happy.
I don't have a lot to say about it. This is so I can find the STUPID LINE OF CODE AGAIN!!!
Everytime I need it, I spend hours digging through code and searching online.
Now it's in my blog and I should be able to find it again.
Keywords I use to search for this on the last round that might help the googles pick this up for the next time I search. Almost like SEO, but more like I DON'T CARE JUST GIVE ME MY BLOG POST
proper way to throw C#
rethrow C#
rethrow C# multithread
C# best way to rethrow an exception
throw C# multithread
throw in .NET code
Thanks for dealing with my find it later post.
UPDATE: 2023-01-22
I created myself this extension method to encapsulate this throwing mechanism AND to help ignore the need for the unreachable throw
.
public static class ExceptionExtensions
{
public static Exception ThrowMe(this Exception ex)
{
ExceptionDispatchInfo.Capture(ex).Throw();
return new UnreachableException("The compiler just doesn't understand our love.");
}
}
And this is used in the calling catch block as
catch (Exception ex)
{
throw ex.ThrowMe();
}
Since the ThrowMe
throws, the throw
will never be hit. If it is... well... you've got other issues.