gpt4 book ai didi

IO 操作期间的 Haskell IO 错误处理

转载 作者:行者123 更新时间:2023-12-01 03:50:43 24 4
gpt4 key购买 nike

System.Directory图书馆,getPermissions函数可能会返回 IO 错误。
文档说它可能会失败 isPermissionErrorisDoesNotExistError .
如何在调用过程中处理 IO 错误 getPermissions ?

试图:

input <- try (do 
permissions <- getPermissions filepath
print permissions)
case input of
Left e -> print "a"
Right e -> print "b"

错误:
No instance for (Exception e0) arising from a use of ‘try’
The type variable ‘e0’ is ambiguous
Note: there are several potential instances:
instance Exception NestedAtomically
-- Defined in ‘Control.Exception.Base’
instance Exception NoMethodError
-- Defined in ‘Control.Exception.Base’
instance Exception NonTermination
-- Defined in ‘Control.Exception.Base’
...plus 7 others
In a stmt of a 'do' block:
input <- try
(do { permissions <- getPermissions filepath;
print permissions })
In the expression:
do { input <- try
(do { permissions <- getPermissions filepath;
print permissions });
case input of {
Left e -> print "a"
Right e -> print "b" } }
In an equation for ‘checkwritefilepermissions’:
checkwritefilepermissions filepath
= do { input <- try
(do { permissions <- getPermissions filepath;
print permissions });
case input of {
Left e -> print "a"
Right e -> print "b" } }

最佳答案

该错误消息表示无法确定您想要捕获的异常类型(即 Exception 的实例)。一种可能的解决方案是提供一个类型注释来指定它,如下所示:

case (input :: Either IOError String) of
Left e -> print "a"
Right r -> print "b"

或者,如果您使用 isDoesNotExistError和 friend 在 System.IO.Error 为了区分错误情况,异常类型将被推断为 IOError不需要额外的注释。

有关基本异常捕获实践的相关讨论可以在 the Control.Exception documentation 中找到。 .

关于IO 操作期间的 Haskell IO 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23172689/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com