I'm trying to write a function where only two method calls (with the methods being unit -> unit) should have a certain exception handled. The behaviour should be:
- if an exception is raised the entire function ends
- the function goes on (outside of the exception handler) otherwise
At first I thought I could use a function with the statements wrapped in a try/with block and a continuation, but of course the continuation would be called from within the block...I could probably wrap the statements in a function and use a return value to signal success/failure, however that looks clunky to me compared to the following C# code, which does what I'm trying to achieve in F#.
SomeType MyMethod(string x)
{
...
try
{
foo();
bar();
}
catch(SomeException)
{
return null;
}
...
return ...;
}
Something like this?
// f <- foo(); bar(); etc...
// k <- unprotected continuation
let runProtected f k =
if try f(); true with _ -> false
then k()
else null
// sample from the question
let runProtected () =
if try
foo(); bar();
true
with _ ->
false
then unprotected()
else null
I think best idiomatic code is using an option type:
member t.MyMethod(x : string) : SomeType =
let result =
try
foo()
bar()
Some(...)
with :? SomeException ->
None
match(result)
| Some(...) -> // do other work and return something
| None -> // return something
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With