dotnet / dotnet/dotnet-api-docs
UnhandledExceptionEventArgs.ExceptionObject docs say it might not be an exception instance, seemingly incorrectly
- 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();
```

```xml
Exe
net48
9
```
Same with `net5.0`.
Contributor guide
Assessment
This issue has not been assessed yet.