Exception handling in Haskell

后端 未结 4 512
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 04:57

I need help to understand the usage of the three Haskell functions

  • try (Control.Exception.try :: Exception e => IO a -> IO (Either e a))
4条回答
  •  醉梦人生
    2020-12-02 05:43

    Re: question 3: catch and handle are the same (found through hoogle). The choice of which to use will usually depend on the length of each argument. If the action is shorter, use catch and vice versa. Simple handle example from the documentation:

    do handle (\NonTermination -> exitWith (ExitFailure 1)) $ ...
    

    Also, you could conceivably curry the handle function to make a custom handler, which you could then pass around, eg. (adapted from documentation):

    let handler = handle (\NonTermination -> exitWith (ExitFailure 1))
    

    Custom error messages:

    do       
        let result = 5 `div` 0
        let handler = (\_ -> print "Error") :: IOException -> IO ()
        catch (print result) handler
    

提交回复
热议问题