Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Exception Handling for part of function

Tags:

exception

f#

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 ...;
}
like image 704
em70 Avatar asked Dec 05 '25 07:12

em70


2 Answers

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
like image 160
desco Avatar answered Dec 08 '25 17:12

desco


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
like image 20
Stringer Avatar answered Dec 08 '25 18:12

Stringer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!