簡體   English   中英

如何在Haskell中處理此簡單的IO異常

[英]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
    ...

除了交換參數外, handlecatch相同。 它進行可能會引發異常的IO計算,某種異常類型的處理程序,然后運行該計算,以捕獲該特定類型的異常。

由於您可能無法返回適當的FilePath列表,因此您可能想捕獲更高級別的異常,例如walk dir = handle handler $ do ... ,然后可以簡單地使用IOException -> IO ()類型的處理程序IOException -> IO ()

由於在這種情況下,我們對所使用的IO異常感興趣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM