Reputation: 4680
Haskell is givinig me a headache today. I want to handle an exception. When it gets to the top it prints like this:
*** Exception: ../p/trip/Trip.hs:(88,16)-(89,50): Non-exhaustive patterns in function split
To me it looks like it is PatternMatchFail, but this doesn't work:
handle (\(PatternMatchFail _) -> return env) f
I mean, it compiles, but doesn't handle the exception. What am I doing wrong? Is this the wrong exception or what? Is there a way to catch any exception?
Upvotes: 3
Views: 306
Reputation: 840
If fixing the source of the error is not an option, you should look at this: http://www.haskell.org/ghc/docs/latest/html/libraries/base/Control-Exception.html
I believe using "handle" or "try" or "catch" or whatever from Control.Exception is the key here, the functions in the standard prelude only deal with IO-Exceptions, not with errors in pure code.
In Haskell98, pure code cannot deal with exceptions. Pure functions must return a value, an exception is a failure to return a value.
Example:
import qualified Control.Exception as C
x ::String
x = undefined
y = "return value"
main = do C.handle (\_ -> return "caught") (C.evaluate x) >>= print
C.handle (\_ -> return "caught") (C.evaluate y) >>= print
The call to evaluate is to force the evaluation of x and y, haskell being lazy and all.
If you let the evaluation of x be deferred until later (lazily), the exception will also be thrown later, in a different place (in this case it is "print" that uses the value), where it may not be caught.
Upvotes: 1