the code below produces a "non-exhaustive pattern in function asd"
data Token = TokenPlus
| TokenMinus
| TokenMal
| TokenGeteilt
| TokenKlammerAuf
| TokenKlammerZu
| TokenInt Int
deriving(Eq,Show)
asd (x:xs) = if x == '+' then (x, TokenPlus): (asd xs)
else (x, TokenInt 1): (asd xs)
Let's say i wanted to catch this kind of error, i would use catch (asd "my_string") my_handler_function
. Fine until here, but what Type is ":t 'non-exhaustive pattern' "
made of ?
Pattern match failure exceptions are of type PatternMatchFail
. The base exceptions are all defined in Control.Exception.
Below is a use of Control.Exception.catch to catch a pattern match failure of the type you're talking about. Here, my operation and handler are both of type IO ()
, but you
can make it anything you want - if the operatio is IO Int
then the exception handler could return a default IO Int
.
{-# LANGUAGE ScopedTypeVariables #-}
import Control.Exception as X
func = X.catch (print $ asd []) printErr
printErr :: SomeException -> IO ()
printErr e = do
case fromException e of
Just (x:: PatternMatchFail) -> putStrLn "I caught the exception"
>> print x
nothing -> return ()
asd :: [Int] -> [Int]
asd (x:xs) = xs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With