haskell - 为什么我不能在 Haskell 中捕获与 () 不同的 IO 中的异常?

标签 haskell exception

我想捕获 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/

相关文章:

haskell - 使用 DataKinds 扩展时如何导出类型构造函数?

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

c# - .NET 中的 WebRequest 异常

java - 断言 java 中私有(private)方法抛出异常的另一种方法

haskell - ghc-mod 期望 MonadBaseControl 具有 `StM` 关联的新类型而不是 `StT` 关联的类型

haskell - 在atom中使用haskell - ghc mod错误

Haskell:如何告诉 hlint 不要: `Warning: Use string literal`

Haskell术语: meaning of type vs.数据类型,它们是同义词吗?

python - 如何检查正则表达式是否完全匹配字符串,即 - 字符串不包含任何额外字符?

powershell - 从try/catch PowerShell中排除终止错误