Ever catched a NULL exception?

In a C# try ... catch block, can the catched Exception be null? Obviously it can’t, although there are situations in which the debugger might interpret it as being null.

For example, consider a try clause followed by multiple catch blocks, to handle different types of exceptions differently. In this case, the above-mentioned scenario can occur (although it does not happen in all of those scenarios, and unfortunately I could not work out which setup consistently reproduces the problem).

try
{
    // do something that fails
}
catch (System.Runtime.InteropServices.COMException e) when (e.HResult == unchecked((int)0x80045509))
{
    // log...
}
catch (Exception e)
{
    // log...
}

It seems that in debug mode, the IL code is optimized somehow, so that the compiler mixes up the two exception objects. Note that both local exception variables are called e? When hitting a breakpoint in line 10, the first variable named e isn’t filled obviously, and in some cases the debugger seems to show the content of this one instead of Exception e.

After all, there is a simple fix, in case this should happen to you at some point: Simply name the two objects differently, to ensure that both can easily be distinguised by compiler and debugger:

try
{
    // do something that fails
}
catch (System.Runtime.InteropServices.COMException e1) when (e1.HResult == unchecked((int)0x80045509))
{
    // log...
}
catch (Exception e2)
{
    // log...
}