dotnet / dotnet/dotnet-api-docs

UnhandledExceptionEventArgs.ExceptionObject docs say it might not be an exception instance, seemingly incorrectly

Open
#5,428 2 comments 0 reactions 2 assignees Claimed by @tannergooding View on GitHub
area-System.Runtime Pri3 untriaged
Dominant language
C#
Stars
949
Forks
1.7k
Avg merge
3d 27m
Merged PRs (30d)
49

Description

https://docs.microsoft.com/en-us/dotnet/api/system.unhandledexceptioneventargs.exceptionobject#remarks:

> This property returns an object of type Object rather than one derived from Exception. Although the Common Language Specification requires that all exception types derive from Exception, it is possible for methods to throw exceptions with objects not derived from Exception. You can do the following to work with this exception:
>
> 1. Apply the RuntimeCompatibilityAttribute attribute with a RuntimeCompatibilityAttribute.WrapNonExceptionThrows value of `true` to the assembly that contains the event handler. This wraps all exceptions not derived from the Exception class in a RuntimeWrappedException object. You can then safely cast (in C#) or convert (in Visual Basic) the object returned by this property to an Exception object, and retrieve the original exception object from the RuntimeWrappedException.WrappedException property. Note that some compilers, such as the C# and Visual Basic compilers, automatically apply this attribute.
>
> 2. Cast the object returned by this property to an Exception object.

But this seems to disagree with https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.runtimewrappedexception#remarks which says:

> Note that the runtime still wraps exceptions even if you use the RuntimeCompatibilityAttribute class to specify that you do not want them wrapped. In this case, exceptions are unwrapped only inside catch blocks or exception filters.

So I tested it, and guess what? `UnhandledExceptionEventArgs.ExceptionObject` seems to always be wrapped no matter what you do:

```cs
using System;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = false)]

AppDomain.CurrentDomain.UnhandledException += (_, e) => Console.WriteLine(e.ExceptionObject.GetType());

Expression.Lambda(Expression.Throw(Expression.New(typeof(object)))).Compile().Invoke();
```

![image](https://user-images.githubusercontent.com/8040367/110987765-928eae00-833d-11eb-84e3-f93f516546af.png)

```xml


Exe
net48
9

```

Same with `net5.0`.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.