handle with SomeException is ignored

时间:2019-04-23 15:10:52

标签: haskell exception functional-programming

I have a usual haskell code which reads file and handle any exception:

handle ((\_->return "ERROR") :: SomeException -> IO String) $ readFile "file.txt"

When I try to read bad encoded file I always get error:

*** Exception: file.txt: hGetContents: invalid argument (invalid byte sequence)

and program is not going to enter to the my exception handle function. I also tried to use IOError and IOException types instead of SomeException but it changes nothing.

If I open similar file with by handle and read it with code:

handle ((\_->return "ERROR") :: SomeException -> IO String) (hGetContents myHandle)

works fine.

How to catch exceptions thrown by hGetContents passed by readFile right way?

1 个答案:

答案 0 :(得分:5)

您可以强制在catch范围内读取整个字符串:

Control.Exception.handle
      ((\_ -> return "ERR") :: Control.Exception.SomeException -> IO String)
      (Prelude.readFile "file.txt" >>= \res -> res `deepseq` (pure res))
"ERR"