dotnet / dotnet/fsharp

`RuntimeWrappedException` cannot be caught

Open
#18,374 4 comments 0 reactions 0 assignees View on GitHub
Area-Compiler-CodeGen Bug Impact-Low
Dominant language
F#
Stars
4.3k
Forks
876
Avg merge
4d 22h
Merged PRs (30d)
144

Description

When a non-`Exception` object is thrown (from CIL or other languages that support it), it cannot be caught in F# by default.

**Repro steps**

```fs
let throwobj (x:obj) = (# "throw" x #) // or any other code that throws a non-Exception instance

try
throwobj "test"
with
| e -> printf "%O" e
```

**Expected behavior**

The exception should be caught either as `System.String` or [`System.Runtime.CompilerServices.RuntimeWrappedException`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.runtimewrappedexception).

**Actual behavior**

> Unhandled exception. System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Exception'.

This is caused by the generated exception handler:
```cil
.try
{
ldstr "test"
throw
// ...
}
catch [netstandard]System.Object
{
castclass [System.Runtime]System.Exception // InvalidCastException
stloc.0
// ...
}
```
F# here catches everything, but the cast to `Exception` throws another exception since the object is not an `Exception`.

**Known workarounds**

The code above succeeds if the [attribute](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.runtimecompatibilityattribute) that controls how wrapped exceptions are exposed is used explicitly:
```fs
[]do()
```

**Related information**

Throwing a `RuntimeWrappedException` manually does not exhibit this behaviour because the runtime does not treat it as a special case then and does not unwrap the value.

Environment: https://sharplab.io/#v2:DYLgZgzgNALiCWwA+wCmMAEMAWAnA9gO74BGAVhgBQAeIpZAlBgLxUDEGARDgYZxtQxsGAWABQ4mLgCe4jFjxF6XGKggxO4wvBzikGVBgC0APgwAHXPAB2MMFwCkAeX6ogA=

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.