本文介绍了如何在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"


推荐答案

您需要一个处理程序来捕获,并匹配 DivideByZero

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

这篇关于如何在Haskell中捕获除零错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 23:19