Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch a divide by zero error in Haskell?

Tags:

haskell

For something like file not found the basic structure of the code below will work, but for this example of division by zero the exception is not caught. How does one catch a divide by zero?

import Control.Exception.Base
import Data.Array

main = toTry `catch` handler

toTry = do
    print "hi"
    print (show (3 `div` 0))
    print "hi"

handler :: IOError -> IO ()
handler e = putStrLn "bad"
like image 708
user782220 Avatar asked Dec 29 '13 05:12

user782220


People also ask

How do you catch a divide by zero exception?

Any number divided by zero gives the answer “equal to infinity.” Unfortunately, no data structure in the world of programming can store an infinite amount of data. Hence, if any number is divided by zero, we get the arithmetic exception .

Which is the divide by zero error?

Microsoft Excel shows the #DIV/0! error when a number is divided by zero (0). It happens when you enter a simple formula like =5/0, or when a formula refers to a cell that has 0 or is blank, as shown in this picture.

What happens if you divide by zero in assembly?

Any number divided by 0 is undefined, mathematically speaking.

How does Div work in Haskell?

The div function requires arguments whose type is in the class Integral, and performs integer division. More precisely, div and mod round toward negative infinity. Their cousins, quot and rem , behave like integer division in C and round toward zero.


1 Answers

You need a handler that catches an ArithException, and matches on DivideByZero.

import Control.Exception.Base
import Data.Array

main = toTry `catch` handler

toTry = do
    print "hi"
    print (show (3 `div` 0))
    print "hi"

handler :: ArithException -> IO ()
handler DivideByZero = putStrLn "Divide by Zero!"
handler _ = putStrLn "Some other error..."
like image 119
YellPika Avatar answered Sep 22 '22 14:09

YellPika