[Haskell] How do I handle errors and exceptions in Haskell?

In Haskell, errors and exceptions are handled using the Either type and the Maybe type. Here's how you can handle errors and exceptions in Haskell:

  1. Using Either type:

    • Either is a type that represents a value that can be either a success Right value or a failure Left value.
    • You can use the Left constructor to represent an error or exception, and the Right constructor to represent a successful result.
    • Here's an example of a function that divides two numbers, handling the error when dividing by zero:
    1divide :: Double -> Double -> Either String Double
    2divide _ 0 = Left "Cannot divide by zero!"
    3divide x y = Right (x / y)
    
    • In the example above, if the second number is 0, it returns a Left value with an error message. Otherwise, it returns a Right value with the result of the division.
  2. Using Maybe type:

    • Maybe is a type that represents a value that can be either Just a value or Nothing.
    • You can use Just to represent a successful result, and Nothing to represent an error or exception.
    • Here's an example of a function that finds the reciprocal of a number, handling the error when the number is zero:
    1reciprocal :: Double -> Maybe Double
    2reciprocal 0 = Nothing
    3reciprocal x = Just (1 / x)
    
    • In the example above, if the input number is 0, it returns Nothing. Otherwise, it returns Just the reciprocal of the number.

By using the Either or Maybe type, you can handle errors and exceptions in Haskell in a functional and type-safe way, avoiding runtime errors and promoting code correctness.