Haskell exception warning but not with OldException

Why does this code work with

import qualified Control.OldException as E 

but not with

 import qualified Control.Exception as E 

Here is the code:

  fileContents <- (readFile "shpm.txt") `E.catch` (\_ -> return "") 

Here is the error I get with the "new" Exception

 Ambiguous type variable `e0' in the constraint: (E.Exception e0) arising from a use of `E.catch' Probable fix: add a type signature that fixes these type variable(s) In a stmt of a 'do' block: fileContents <- (readFile "shpm.txt") `E.catch` (\ _ -> return "No Tasks") 
+4
source share
2 answers

Because the types have changed. In particular:

  • OldException: catch :: IO a -> (Exception -> IO a) -> IO a
  • Exception: catch :: Exception e => IO a -> (e -> IO a) -> IO a

The new model should know that the value of e for type Exception e . In fact, this means that you need to tell the compiler which exception you are catching. Your OldException example catches everything that is now discouraging (see "Catching All Exceptions" for more information).

A simple fix for your function would look something like this:

 foo = (readFile "foo") `E.catch` (\e -> const (return "") (e :: E.IOException)) 

Or without lambda version:

 bar = (readFile "foo") `E.catch` myHandler myHandler :: E.IOException -> IO String myHandler _ = return "" 
+9
source

You need to specify the type of exception to exclude. For instance:

 fileContents <- (readFile "shpm.txt") `E.catch` ((\_ -> return "") :: E.SomeException -> IO String) 
+1
source

Source: https://habr.com/ru/post/1432857/


All Articles