[Haskell-cafe] does try force evaluation of IO value
Roman Cheplyaka
roma at ro-che.info
Fri Oct 5 13:07:12 CEST 2012
* s9gf4ult at gmail.com <s9gf4ult at gmail.com> [2012-10-05 16:52:52+0600]
> > No, it won't force the return value. To do that, use evaluate
> > http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Exc
> > eption-Base.html#g:7
> But what is happening when exception is raised when consuming value from
> result of "try" ?
> try has signature
> try :: Exception e => IO a -> IO (Either e a)
> so it must return either exception value either evaluated value and must not
> raise exceptions, but how can "try" return (Right a) wthout making sure that
> action will not raise any exception ?
There's no promise that the returned lazy value won't throw any
exceptions. Example:
Prelude Control.Exception> r <- try (return $ error "bam") :: IO (Either SomeException Int)
Prelude Control.Exception> r
Right *** Exception: bam
try will only catch exceptions that arise from executing the IO action.
If you need to be sure that no exception will be raised, you need to
force it yourself, like this:
Prelude Control.Exception> r <- try (evaluate $ error "bam") :: IO (Either SomeException Int)
Prelude Control.Exception> r
Left bam
If the return type is a lazy structure, you may also need to use deepseq
('evaluate' only evaluates to WHNF).
Roman
More information about the Haskell-Cafe
mailing list