Anton
Anton

Reputation: 2585

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]

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

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

Thanks for help.

Upvotes: 7

Views: 911

Answers (2)

Don Stewart
Don Stewart

Reputation: 137957

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)

Upvotes: 7

geekosaur
geekosaur

Reputation: 61379

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

Upvotes: 4

Related Questions