haskell - Handling exceptions thrown by pure code with `try` -
i playing exceptions in haskell , stumbled upon 1 thing can't understand yet.
in ghci do:
prelude control.exception> let thrower = (read "a") :: int prelude control.exception> :{ prelude control.exception| let main = prelude control.exception| x <- (try $ return thrower) :: io (either someexception int) prelude control.exception| print x prelude control.exception| :} prelude control.exception> main
this defines thrower
, test expression fail exception.
then define main
wraps expression try
(wrapping io
first, since try
accepts io
) , unwraps io
(produced try
) , print
s it.
everything looks great far - evaluating main
in repl gives exception wrapped either:
right *** exception: prelude.read: no parse
however, if try compile , execute same code app:
module main import control.exception thrower = (read "a") :: int main = x <- (try $ return thrower) :: io (either someexception int) print x
... gets crashed exception:
haskelltest.exe: prelude.read: no parse
it seems exception slipped past try
.
what missing here , correct way handle this?
well, (as sebastian redl pointed out earlier) strictness issue. return thrower
not in way evaluate thrower
, try
succeeds. when content of either someexception int
printed, namely right thrower
, read
try parse "a"
, , fails... @ point, try
over.
the way prevent inject parse result strictly io
monad, with
main = x <- try $ evaluate thrower :: io (either someexception int) print x
why try
fails code in ghci don't know; daresay shouldn't. aha: as reid noted, it doesn't fail actually!
arguably, example why exceptions should avoided in haskell. use suitable monad transformer make explicit errors might occur, , reliable evaluation of error-checking.
Comments
Post a Comment