我想捕获 IO String 函数中的所有异常。当我运行此代码时:
import Control.Exception.Base
handler :: SomeException -> IO String
handler _ = return "Gotta catch'em all!"
boom :: IO String
boom = return (show (3 `div` 0))
get :: IO String
get = boom `catch` handler
main :: IO()
main = do
x <- get
print x
我明白了
exctest: divide by zero
但是这段代码可以工作:
import Control.Exception.Base
handler2 :: SomeException -> IO ()
handler2 _ = print "Gotta catch'em all!"
boom2 :: IO ()
boom2 = print $ show (3 `div` 0)
main :: IO()
main = do
boom2 `catch` handler2
结果
> Gotta catch'em all!
当我将第一个示例中的繁荣更改为
boom = error "ERR"
异常捕获正常。为什么它会这样?在第一个示例中我应该如何捕获异常?
最佳答案
这与 ()
与其他类型无关。请注意,以下内容也不会捕获:
boom = return $ error "ERR"
catch
不会对此做任何事情的原因是 return
是惰性的,因此错误实际上并不是由 catch
触发的,仅当您尝试获取包含的值时。
正是由于这个原因,Exception
模块具有 evaluate ,相当于 return
但严格。
boom :: IO String
boom = evaluate . show $ 3`div`0
关于haskell - 为什么我不能在 Haskell 中捕获与 () 不同的 IO 中的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43397911/