user782220
user782220

Reputation: 11207

How to catch a divide by zero error in 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"

Upvotes: 7

Views: 2135

Answers (1)

YellPika
YellPika

Reputation: 2902

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..."

Upvotes: 11

Related Questions