Last active
January 19, 2016 07:41
-
-
Save raichoo/0e77824f2c4b22a8fdb3 to your computer and use it in GitHub Desktop.
Example why you should avoid unsafe functions like `read`, or at least be careful.
This file contains hidden or 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
#!/usr/bin/env runhaskell | |
-- run as script to get correct buffering behavior | |
-- >>> chmod +x ./script.hs | |
-- >>> ./script.hs | |
module Main where | |
import Control.Exception | |
example :: IO Int | |
example = | |
prompt `catch` handler -- exception thrown by `read` escapes catch | |
-- (prompt >>= evaluate) `catch` handler -- force evaluation so exception cannot escape | |
-- notice that `evaluate` only evaluates to WHNF. If you have unevaluated thunks inside | |
-- of that the exception still might escape our `catch`. | |
where | |
prompt :: IO Int | |
prompt = read <$> (putStr "> " *> getLine) | |
handler :: SomeException -> IO Int | |
handler _ = do | |
putStrLn "ERROR: invalid input" | |
example | |
main :: IO () | |
main = print =<< example |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment