Why is UnhandledExceptionEventArgs.ExceptionObject an object and not an Exception?
Solution 1
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
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
.
Simon
Feel free to contact me on twitter @simoncropp or [email protected] Software Developer and part time hacker I contribute heavily to many and varied open source projects. I believe in the open source ethos of "Paying it forward".
Updated on June 18, 2022Comments
-
Simon over 1 year
Why is
UnhandledExceptionEventArgs.ExceptionObject
an object and not anException
?I am attaching to
AppDomain.UnhandledException
.I would like to cast
UnhandledExceptionEventArgs.ExceptionObject
to anException
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.
-
Simon over 14 yearsThanks Jared I have added your answer and a link back here to the msdn community content
-
Dennis over 12 yearsThank-you for the information; I was handling this manually, i.e., wrapped it in a RuntimeWrappedException if it failed to cast an exception.
-
Mubashar almost 10 yearsSo casting it to Exception in C# will not be a problem? right?
-
JaredPar almost 10 years@MubasharAhmad it can be a problem if the type isn't derived from
System.Exception
. The exception could've resulted from a non-CLI compliant language which decide to throw aSystem.Int32
. Newer versions of the CLR will auto-wrap this inSystem.Exception
anyways but this is a setting that can be disabled -
david.barkhuizen about 7 years@MubasharAhmad I would recommend that you use the 'as' cast, so that in the case that the object is not derived from type Exception, the cast defaults to null, rather than throwing an exception.
-
AgentFire over 6 yearsWhy then
try-catch
block doesnt allow to catch non-Exception objects? -
Sören Kuklau almost 6 years@AgentFire because, as JaredPar said, C# does not support exceptions that don't derive from Exception. The .NET framework and .NET runtime do, but the C# language does not.