Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# exception filters

Tags:

exception

clr

f#

The article https://devblogs.microsoft.com/dotnet/the-good-and-the-bad-of-exception-filters/ suggests that F# natively supports exception filters (that have no syntax in C#, for instance). Exception filters run before the appropriate catch block and if they return true, the catch block will execute. I would imagine F# does this using something like this

with
    | ex when filter(ex) -> printfn "Caught"

However, for me it compiles to the usual "catch [mscorlib]System.Object" with a call to the filter function inside the catch block and no "filter" section is present in generated MSIL. So the question is, does F# really support this construct?

Thanks

like image 932
actionresult Avatar asked Sep 01 '13 10:09

actionresult


1 Answers

As far as I know, F# does not actually implement/use/expose the filter handlers available in MSIL (ECMA-335, 5th ed., Partition I, Section 12.4.2 "Exception handling"). According to section 6.9.21 of the F# 3.0 language specification, the compiler is supposed to compile the entire with clause into a catch block; a "fall-through" case is added to the compiled code so that if the caught exception does not match any of the patterns in the with clause, it is re-raised (via the rethrow IL instruction).

That said, I'd really like to see F# support more low-level IL/CLR constructs -- they aren't used often, but sometimes they provide the only way to implement something correctly, or they avoid the need for complicated workarounds; and, as in the OP's case, it's important that F# supports these for purposes of interoperability. For example, try...fault would really be handy for logging purposes, and it would simplify some bits of code which currently need to use try...finally with additional logic (e.g., the implementation of lock in FSharp.Core).

UPDATE: I was just searching around for information on a completely different topic, and ran across this post from 2006 on Don's blog: F# 1.1.13 now available! (also see the accompanying release notes). Of course, F# 1.1.13 was a very early version of the language, and it was still quite experimental at that point, but is interesting to see that the compiler once had a --generate-filter-blocks switch.

like image 147
Jack P. Avatar answered Sep 30 '22 02:09

Jack P.