Why is UnhandledExceptionEventArgs.ExceptionObject an object and not an Exception?

.NetExceptionException HandlingUnhandled Exception

.Net Problem Overview


Why is UnhandledExceptionEventArgs.ExceptionObject an object and not an Exception?

I am attaching to AppDomain.UnhandledException.

I would like to cast UnhandledExceptionEventArgs.ExceptionObject to an Exception and interogate it.

And with this in mind will it ever be null?

The MSDN documentation is not exatly useful.

> Gets the unhandled exception object.

.Net Solutions


Solution 1 - .Net

This cannot be typed to Exception because it's possible to throw objects in .Net that do not derive from System.Exception. This is not possible in C# or VB.Net but it is possible in other CLR based languages. Hence the API must support this possibility and uses the type object.

So while it shouldn't ever be null, it may not in fact be a System.Exception.

See CLI spec section 10.5 (specifically CLS rule 40) for more details

Solution 2 - .Net

In addition to what Jared has already mentioned, you can safely cast to Exception in .NET Framework 2.0 and higher if RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true) has been applied to your assembly (will be added automatically by the C# and VB compilers).

When this attribute has been applied, non-Exception "exceptions" will be wrapped in RuntimeWrappedException.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSimonView Question on Stackoverflow
Solution 1 - .NetJaredParView Answer on Stackoverflow
Solution 2 - .NetNicole CalinoiuView Answer on Stackoverflow