Catch block is not being evaluated when exceptions are thrown from finallys

后端 未结 3 1543
粉色の甜心
粉色の甜心 2021-02-12 23:58

This question came about because code that worked previously in .NET 4.0 failed with an unhandled exception in .NET 4.5, partly because of try/finallys. If you want details, re

3条回答
  •  自闭症患者
    2021-02-13 00:33

    Exception processing in .NET has 3 distinct stages:

    • stage 1 kicks in gear as soon as a throw statement executes. The CLR goes looking for a catch block that's in scope that advertizes that it is willing to handle the exception. At this stage, in C#, no code executes. Technically it is possible to execute code but that capability is not exposed in C#.

    • stage 2 starts once the catch block is located and the CLR knows where execution resumes. It can then reliably determine what finally blocks need to be executed. Any method stack frames are unwound as well.

    • stage 3 starts once all finally blocks are completed and the stack is unwound to the method that contains the catch statement. The instruction pointer is set to the first statement in the catch block. If this block contains no futher throw statements, execution resumes as normal at the statement past the catch block.

    So a core requirement in your code snippet is that there is a catch (CryptographicException) in scope. Without it, stage 1 fails and the CLR doesn't know how to resume execution. The thread is dead, usually also terminating the program depending on exception handling policy. None of the finally blocks will execute.

    If in stage 2 a finally block throws an exception then the normal exception handling sequence is immediately interrupted. The original exception is "lost", it never gets to stage 3 so cannot be observed in your program. Exception handling starts back at stage 1, now looking for the new exception and starting at the scope of that finally block.

提交回复
热议问题