开发者

Haskell. Non IO Exception handling

开发者 https://www.devze.com 2023-02-17 17:48 出处:网络
I am trying to catch exception due to with the action ([1,2] !! 3). I can not. I was trying let a = [1,2]

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 M开发者_如何学Pythonaybe approach.

Thanks for help.


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)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消