对于诸如找不到文件之类的东西,下面代码的基本结构将起作用,但是对于这个除以零的示例,不会捕获异常。一个人如何除以零?

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"

最佳答案

您需要一个处理程序来捕获 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..."

关于haskell - 如何在 Haskell 中捕获除以零错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20822365/

10-13 06:39