Last active
August 29, 2015 14:15
-
-
Save JustinSDK/775141f95293290841a6 to your computer and use it in GitHub Desktop.
〈Haskell Tutorial(23)Exception 的 catch 與 handle〉的解答
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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