Why is UnhandledExceptionEventArgs.ExceptionObject an object and not an Exception?
Asked Answered
T

2

135

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.

Thrippence answered 27/5, 2009 at 0:47 Comment(0)
I
156

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

Ibnsaud answered 27/5, 2009 at 0:51 Comment(6)
Thanks Jared I have added your answer and a link back here to the msdn community contentThrippence
So casting it to Exception in C# will not be a problem? right?Gunyah
@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 a System.Int32. Newer versions of the CLR will auto-wrap this in System.Exception anyways but this is a setting that can be disabledIbnsaud
@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.Moulder
Why then try-catch block doesnt allow to catch non-Exception objects?Oleic
@Oleic 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.Laminate
D
83

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.

Decorticate answered 17/9, 2009 at 15:30 Comment(1)
Thank-you for the information; I was handling this manually, i.e., wrapped it in a RuntimeWrappedException if it failed to cast an exception.Dealt

© 2022 - 2024 — McMap. All rights reserved.