如何在Haskell中捕获零误差?

时间:2013-12-29 05:10:57

标签: haskell

对于未找到文件的内容,下面代码的基本结构将起作用,但对于此除零的示例,不会捕获异常。人们如何得到除以零的分数?

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"

1 个答案:

答案 0 :(得分:10)

您需要一个捕获ArithException的处理程序,并匹配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..."