![](/img/trans.png)
[英]how to use haskell Control. Exception handle to return a IO(Maybe a)
[英]How to handle this simple IO exception in Haskell
處理所有:
在以下代碼中, getDirectoryContents dir
可能會失敗。 例如, dir
可能不存在。 如何捕捉到這一點並向用戶傳達有意義的信息? 我知道IO異常處理已被問過很多次,但是我仍然找不到簡單的方法來做到這一點。
walk :: FilePath -> IO()
walk dir = do
contentsFullPath <- getDirectoryContents dir >>= removeDotFile >>= getFullPath
dirList <- filterM doesDirectoryExist contentsFullPath
fileList <- filterM doesFileExist contentsFullPath
forM_ fileList processFile >> forM_ dirList walk
where
removeDotFile = return . filter (`notElem` ["..", "."])
getFullPath = return . zipWith ( </> ) (repeat dir)
processFile = getFileSize
您正在尋找Control.Exception
模塊及其大量用於捕獲/處理異常的功能,
在你的情況下
handler :: IOException -> IO [FilePath]
handler = undefined
walk :: FilePath -> IO()
walk dir = do
contentsFullPath <- handle handler $
getDirectoryContents dir
>>= removeDotFile
>>= getFullPath
...
除了交換參數外, handle
與catch
相同。 它進行可能會引發異常的IO
計算,某種異常類型的處理程序,然后運行該計算,以捕獲該特定類型的異常。
由於您可能無法返回適當的FilePath
列表,因此您可能想捕獲更高級別的異常,例如walk dir = handle handler $ do ...
,然后可以簡單地使用IOException -> IO ()
類型的處理程序IOException -> IO ()
。
由於在這種情況下,我們對所使用的IO
異常感興趣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.