Try-Catch-Finally block issues with .NET4.5.1

前端 未结 1 766
孤街浪徒
孤街浪徒 2021-02-18 14:43

I have a simple test code that works as expected in .NET3.5, but the same code behaves completely different on a project created with .NET4.5.1.

class Program
{
         


        
相关标签:
1条回答
  • 2021-02-18 15:05
    string a = null;
    var x = a.Length;
    

    In RELEASE mode, the jitter (just in time compiler) is able to prove that x is never referenced, so is able to remove the assignment.

    In DEBUG mode, the jitter does not perform that optimization.

    To force the exception to be thrown, do something with x (e.g. as @Henk suggests in the comments, WriteLine(x)).

    EDIT

    Eric Lippert noted in the comments

    ...I am as surprised as anyone that the jitter would elide a string length instruction that could throw. That seems wrong to me...

    The jitter optimization may be overly-aggressive.

    0 讨论(0)
提交回复
热议问题