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

后端 未结 3 1529
粉色の甜心
粉色の甜心 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:53

    If an exception is thrown during execution of a finally block, and an exception was already being propagated, that exception is lost

    Basically, what's happening when you execute:

    • CryptographicException is thrown in inner finally.
    • Outer-scope finally executes, and throws ArgumentException. Since "CryptographicException" was "being propogated" at this point in time, it is lost.
    • Final catches occur, and ArgumentException is caught.

    ... and it wouldn't make sense for the first exception to simply disappear into the ether, just because there was another exception thrown from a different finally block.

    This is exactly what happens, based on the C# language specification you quoted. The first exception (CryptographicException) effectively disappears - it's "lost".

    You can only reach this state by explicitly using finally, though, so I believe the assumption is that you're providing the error handling with this expectation or possibility in mind (as you're using try at that point, which means you've accepted you may have an exception).

    This is basically explained in detail in the spec in 8.9.5 (the text in 8.10 you quoted refers to this section):

    If the finally block throws another exception, processing of the current exception is terminated.

    The first exception, in your case the ArgumentException, basically "disappears".

提交回复
热议问题