134

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.

wonea
  • 4,783
  • 17
  • 86
  • 139
Simon
  • 33,714
  • 21
  • 133
  • 202

2 Answers2

155

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

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 3
    Thanks Jared I have added your answer and a link back here to the msdn community content – Simon May 27 '09 at 01:02
  • So casting it to Exception in C# will not be a problem? right? – Mubashar Nov 28 '13 at 00:34
  • 2
    @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 disabled – JaredPar Nov 30 '13 at 00:07
  • 1
    @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. – david.barkhuizen Sep 12 '16 at 11:39
  • Why then `try-catch` block doesnt allow to catch non-Exception objects? – AgentFire Jun 16 '17 at 16:18
  • @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. – Sören Kuklau Dec 07 '17 at 09:38
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.

Dennis
  • 20,275
  • 4
  • 64
  • 80
Nicole Calinoiu
  • 20,843
  • 2
  • 44
  • 49
  • 3
    Thank-you for the information; I was handling this manually, i.e., wrapped it in a RuntimeWrappedException if it failed to cast an exception. – Dennis Jul 21 '11 at 10:48