Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 忽略带有SomeException的句柄_Haskell_Exception_Functional Programming - Fatal编程技术网

Haskell 忽略带有SomeException的句柄

Haskell 忽略带有SomeException的句柄,haskell,exception,functional-programming,Haskell,Exception,Functional Programming,我有一个常见的haskell代码,可以读取文件并处理任何异常: handle((\\\->return“ERROR”)::SomeException->IO String)$readFile“file.txt” 当我尝试读取错误编码的文件时,总是会出现错误: *** Exception: file.txt: hGetContents: invalid argument (invalid byte sequence) 程序不会进入我的异常句柄函数。我还尝试使用IOError和IOExcepti

我有一个常见的haskell代码,可以读取文件并处理任何异常:

handle((\\\->return“ERROR”)::SomeException->IO String)$readFile“file.txt”
当我尝试读取错误编码的文件时,总是会出现错误:

*** Exception: file.txt: hGetContents: invalid argument (invalid byte sequence)
程序不会进入我的异常句柄函数。我还尝试使用
IOError
IOException
类型,而不是
SomeException
,但它没有任何改变

如果我用by handle打开类似的文件并用代码读取它:

handle((\ \ \->return“ERROR”)::SomeException->IO String(hGetContents-myHandle)
很好


如何正确捕获由
readFile
传递的
hGetContents
引发的异常?

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

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

readFile
只是在返回字符串后才执行惰性IO读取文件,这难道不是一件好事吗?尝试在
句柄中强制计算字符串
@Bergi,我在ghci中运行此代码,因此结果是强制的immediately@Shadasviar这并不意味着Bergi的诊断是错误的,它实际上支持了猜测。1.运行readFile,获取一些字节(或者可能还没有字节!)2。返回一个(惰性)
字符串
,因此现在不再在
句柄中
。3.尝试在REPL上打印整个字符串,从而强制读取所有字符串。4.遇到错误并引发异常。