F # Handling exceptions for part of a function

I am trying to write a function in which only two method calls (using unit → unit methods) must have a specific exception handled. The behavior should be:
- if an exception occurs, the entire function ends
- the function continues (outside the exception handler) otherwise, at



first it seemed to me that I could use the function with statements enclosed in a try / with block and a continuation, but, of course, the continuation will be being called from within the block ... I could probably transfer the statements to a function and use the return value to confirm success / failure, however this looks awkward for me compared to the following C # code that does what I'm trying Referring to achieve in F #.

SomeType MyMethod(string x)
{
    ...
    try
    {
        foo();
        bar();
    }
    catch(SomeException)
    {
        return null;
    }
    ...
    return ...;
}
+3
4

- ?

// 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
+4

, :

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
+2

What about:

let success =
    try
        foo ()
        bar ()
        true
    with :? SomeException ->
        false

if success then
    ...
else
    ()
0
source

Well ... you could do ...

type Test() =
    member this.MyMethod (x:string) =
        if try
            foo()
            bar()
            true
           with _ -> false
        then
            // do more work
            "blah"
        else
            null

Or, flip true / false ...

type Test() =
    member this.MyMethod (x:string) =
        if try
            foo();
            bar();
            false
           with _ -> true
        then
            // bail early
            null
        else
            // do more work
            "blah"

I highly recommend switching from zero to return the option type (Some (x) / None). Let the compiler catch places where null is not processed, not your users; -)

0
source

Source: https://habr.com/ru/post/1754207/


All Articles