Skip to content

Instantly share code, notes, and snippets.

@raichoo
Last active January 19, 2016 07:41
Show Gist options
  • Save raichoo/0e77824f2c4b22a8fdb3 to your computer and use it in GitHub Desktop.
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.
#!/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