Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Last active August 29, 2015 14:15
Show Gist options
  • Save JustinSDK/775141f95293290841a6 to your computer and use it in GitHub Desktop.
Save JustinSDK/775141f95293290841a6 to your computer and use it in GitHub Desktop.
〈Haskell Tutorial(23)Exception 的 catch 與 handle〉的解答
import Data.Typeable
import Prelude hiding (catch, readFile)
import Control.Exception hiding (finally)
import System.Environment
import System.IO hiding (readFile)
readFile :: FilePath -> IO String
readFile fileName =
bracket (openFile fileName ReadMode) hClose (\handle -> do
contents <- hGetContents handle
evaluate contents
return contents)
main =
(do (fileName:_) <- getArgs
contents <- readFile fileName
putStrLn contents)
`catches`
[Handler (\(_::IOException) -> putStrLn "發生 IOException ..."),
Handler (\(e::SomeException) -> print $ typeOf e)]
`finally` (putStrLn "finally 執行最後資源善後")
finally :: IO a -> IO b -> IO a
finally a1 a2 = bracket (return ()) (\_ -> a2) (\_ -> a1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment