在System.Directory库中,getPermissions函数可能返回IO错误.
文档说它可能会因isPermissionError或isDoesNotExistError而失败.
如何在调用getPermissions期间处理IO错误?
尝试:
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"
或者,如果在System.IO.Error
中使用isDoesNotExistError和friends来区分错误情况,则异常类型将被推断为IOError,而不需要额外的注释.
有关基本异常捕获实践的相关讨论可在the Control.Exception
documentation中找到.