[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:

Using
Either
type:Either
is a type that represents a value that can be either a successRight
value or a failureLeft
value. You can use the
Left
constructor to represent an error or exception, and theRight
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 aRight
value with the result of the division.

Using
Maybe
type:Maybe
is a type that represents a value that can be eitherJust
a value orNothing
. You can use
Just
to represent a successful result, andNothing
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 returnsJust
the reciprocal of the number.
By using the Either
or Maybe
type, you can handle errors and exceptions in Haskell in a functional and typesafe way, avoiding runtime errors and promoting code correctness.