0

When managed code is being executed by a .Net CLR, what happens if a second exception is thrown whilst the runtime is unwinding the stack due to an initial exception?

This doesn't refer to rethrowing an exception from a Catch block. It covers situations where an exception is thrown whilst the CLR is in the process of unwinding the stack.

In C++, this would cause the program to terminate, but I can't find any documentation about the behaviour in .Net.

andypea
  • 1,343
  • 11
  • 22
  • This isn't the same as the other question as it pertains to exceptions thrown outside of a Catch block. – andypea Feb 10 '21 at 23:03
  • 2
    @Steve Correct duplicate is here https://stackoverflow.com/questions/2911215/what-happens-if-a-finally-block-throws-an-exception – Charlieface Feb 11 '21 at 23:46
  • First answer from my link says "Your finally block will not be completed beyond the point where the exception is thrown. If the finally block was executing during the handling of an earlier exception then that first exception is lost." – Charlieface Feb 14 '21 at 20:44
  • Why can't a second exception been thrown from somewhere other than a finally block? – andypea Feb 14 '21 at 20:46
  • When the stack unwinds, what executes apart from `finally` blocks? Nothing. This is between a `catch` block being identified higher up the stack, and it actually being executed – Charlieface Feb 14 '21 at 20:47
  • Don't finalizers get executed? – andypea Feb 14 '21 at 20:49
  • No. [Finalizers are executed on a separate thread after they are marked by GC](https://stackoverflow.com/questions/5200848/finalizer-not-called), it's a completely separate process. Maybe you are confusing `using` blocks (IDisposable) which under the hood is just a `try/finally` – Charlieface Feb 14 '21 at 20:51
  • Can you point me to your source which describes what happens during a stack unwind? I'm not trying to be a jerk here, I'm genuinely interested in reading about it and can't find much official documentation. – andypea Feb 14 '21 at 20:54
  • 1
    Start [here](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/) maybe, also [ECMA-335 Part I.12.4.2.5](https://www.ecma-international.org/wp-content/uploads/ECMA-335_6th_edition_june_2012.pdf) (this is the spec for the .NET CLR). I sincerely apologize, the one other place an exception can be thrown is the `when` part of a `catch` block – Charlieface Feb 14 '21 at 21:03
  • Thanks. Your comments are really helpful. – andypea Feb 14 '21 at 21:10

0 Answers0