Search code examples
c#c#-6.0.net-native

Code in filtered exception handler throws NullReferenceException when accessing exception


When I compile a UWP app with the .NET Native compiler and turn on code optimizations (essentially release mode), then I get a NullReferenceException when I try to access the actual exception in the catch block.

Code Sample:

try
{
    throw new ArgumentNullException("Param");
}
catch (ArgumentNullException ex) when (ex.ParamName == "Param")
{
    ErrorBlock.Text = ex.ParamName; // ErrorBlock is a TextBlock in the xaml
}
catch (Exception)
{
}

It goes into the correct catch block, and throws a NullReferenceException when I access ex. This only fails if both .Net Native and code optimizations are on.

What causes this issue?


Solution

  • I work on the .NET Native runtime and compiler team.

    This is a bug inside of our compiler. You can think of each exception handling region (try, catch, finally, when) as a small function or "funclet". We lose track of the exception object when setting up the stack for the "when" (aka filter block). This bug is corrected in Windows Tools 1.3 which, given no major setbacks, should be shipping in another week or two. It'll show up as an update for folks that have installed VS 2015 Update 2.

    Let me know if you have any other questions.