Sha*_*iar 4 haskell functional-programming exception
我有一个普通的haskell代码,它读取文件并处理任何异常:
handle ((\_->return "ERROR") :: SomeException -> IO String) $ readFile "file.txt"
Run Code Online (Sandbox Code Playgroud)
当我尝试读取错误的编码文件时,总是出现错误:
*** Exception: file.txt: hGetContents: invalid argument (invalid byte sequence)
Run Code Online (Sandbox Code Playgroud)
并且程序不会进入我的异常处理函数。我也尝试使用IOError和IOException类型代替,SomeException但是它什么也没改变。
如果我使用句柄打开类似文件并使用代码读取它:
*** Exception: file.txt: hGetContents: invalid argument (invalid byte sequence)
Run Code Online (Sandbox Code Playgroud)
工作正常。
如何捕获hGetContents以readFile正确方式传递的异常?
您可以强制在catch范围内读取整个字符串:
Control.Exception.handle
((\_ -> return "ERR") :: Control.Exception.SomeException -> IO String)
(Prelude.readFile "file.txt" >>= \res -> res `deepseq` (pure res))
"ERR"
Run Code Online (Sandbox Code Playgroud)