Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell. Non IO Exception handling

I am trying to catch exception due to with the action ([1,2] !! 3). I can not.

I was trying

let a = [1,2]
  • handle (\(e :: SomeException) -> print "err" >> return 1) (return $ a !! 3)
  • Control.Exception.catch (return $ a !! 3) (\(e::SomeException) -> print "err" >> return 1)

in both i get Exception: Prelude.(!!): index too large*

Is it possible? Probably i am to use Maybe approach.

Thanks for help.

like image 879
Anton Avatar asked Mar 17 '11 19:03

Anton


2 Answers

Laziness and exceptions, like laziness and parallelism, interact in subtle ways!

The return wraps up your array access in a thunk, so that it is returned unevaluated, causing the exception to be evaluated outside of the handler.

The solution is to ensure that evaluating return must also evaluate the list index. This can be done via $! in this case:

handle ((e :: SomeException) -> print "err" >> return 1) (return $! a !! 3)

like image 142
Don Stewart Avatar answered Oct 04 '22 21:10

Don Stewart


This usually means your code is too lazy and the dereference happens after the handler returns. Try using $! instead of $ to force evaluation.

like image 44
geekosaur Avatar answered Oct 04 '22 22:10

geekosaur