Haskell 不像其他语言(如 Python 和 Java)那样进行错误处理。当您调用该error
函数时,程序将停止。时期。无法捕获错误。无法重定向它或重新启动程序。该error
函数引发错误,而不是异常。如果你想在 Haskell 中表示失败的想法,你可以使用Maybe
and Either
monads。下面是您如何使用Either
monad 实现您想要的功能。
main = do
a <- NewIORef (Right 1 :: Either String Int)
modifyIORef a (const $ Left "some execution error")
-- a now holds a "Left" value, representing an error
val <- readIORef a
-- val now holds the "Left" value
case val of
Left err -> putStrLn $ "Error: " ++ err -- prints error (if applicable)
Right val -> putStrLn $ "Result: " ++ show val -- prints value (if applicable)
编辑:正如 dfeuer 在他的评论中指出的那样,可以拦截 GHC 中的错误。但是,除非在非常特殊的情况下,否则它被认为是不好的做法,因此仍然首选使用Maybe
and类型。Either