Morning all,
Bit of a language theory question here... I've found some references online suggesting that exception handling and delegates in C# have some different behaviour in some cases but I cannot find any concrete documentation on the matter.
We recently had some big problems with exceptions inside delegates for a Microsoft Excel addin causing a hard-crash in the MSVC runtime. Removing delegates solved this but I'm now curious to find out the gory details.
As a terse example of the core code:
Delegate del; // initialized elsewhere
try
{
del.DynamicInvoke();
}
catch(Exception e)
{
/* Parsing of exception to generate user-friendly message here */
}
The above construct allowed a centralized form of error handling and from a pure code point of view was clean and concise. Each publicly exposed function was declared as a delegate and executed via the above fragment.
In a simple console app, throwing an exception from the delegate or just a plain unexpected error (e.g. "accidentally" calling ToString() on a null pointer) works as expected and the error is handled as desired.
Throw in MS Excel and you get hard-crashes. Stepping through the code will show where the error occurs but no stack unwinding appears to take place before everything comes down in a big fireball of destruction.
My hypothesis is that COM, hosting the .NET runtime (and hence our code) is doing something different to normal .NET code execution. This kills the end-point and Excel doesn't know this, which in turn tries to access the end-point via COM only to find it has somehow disappeared and Excel craps out in return.
This only happens with the combination of Excel+COM+delegates, but I don't honestly know which is the more influential in this behaviour... any thoughts?