Sunday 1 May 2016

Haskell: Reporting Errors using error function


It is one of the most useful functions to report errors, error function takes a string message and display the message to the console.

Following is the signature of error function.

error :: [Char] -> a

As you observe, it has return type of a, so we can call this from any function, it always has right type. When you call error function from your code, it immediately aborts the execution and prints the error message.

errorUtil.hs
divide x 0 = error "You can't divide a number by 0"
divide x y = x / y


When you call the divide method by passing second argument 0, it throws an Exception immediately.
*Main> :load errorUtil.hs
[1 of 1] Compiling Main             ( errorUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> divide 10 0
*** Exception: You can't divide a number by 0
*Main> 


We can rewrite above program using Maybe data type like below.

errorUtil.hs
divide x 0 = Nothing
divide x y = Just (x / y)

*Main> :load errorUtil.hs
[1 of 1] Compiling Main             ( errorUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> divide 10 0
Nothing
*Main> 
*Main> divide 10 123456
Just 8.100051840331778e-5
*Main>


Whenever you want to throw an error, try to use Maybe.
Another example
Suppose, you car going to implement factorial function, usually factorial os not applicable for -ve numbers, so when user call factorial function with –ve numbers, your function should throw an error.

Sample.hs
factorial :: Int -> Int
factorial num
    | (num == 0) = 1
    | (num > 0) = num * factorial(num-1)
    | otherwise = error "factorial is only defined for +ve integers"

Prelude> :load Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> factorial 0
1
*Main> factorial 5
120
*Main> factorial (-9)
*** Exception: factorial is only defined for +ve integers

Previous                                                 Next                                                 Home

No comments:

Post a Comment