Haskell - catch exception for readFile

I am trying to read a file in Haskell with an exception, but cannot work. The code looks like this:

     module Main where
    import System.Environment
    import System.IO
    import System.Exit

    main = do
        x:xs <- getArgs
        case length(x:xs) of
            2 -> do catch (readFile x)
                        (\_ -> do   putStrLn ("Error on reading file: " ++ x) 
                                    getLine
                                    exitWith ExitSuccess)
            _ -> do putStrLn ("Run this way: ./projekt inputFile RE") >>
                exitFailure

And I get this error:

Couldn't match expected type `IO String
                              -> (ExitCode -> IO a)
                              -> ExitCode
                              -> IO String'
       against inferred type `IO ()'
In the expression:
    putStrLn
      ("Error on reading file: " ++ x) getLine exitWith ExitSuccess
In the expression:
    do { putStrLn
           ("Error on reading file: " ++ x) getLine exitWith ExitSuccess }
In the second argument of `catch', namely
    `(\ _ -> do { putStrLn
                    ("Error on reading file: " ++ x) getLine exitWith ExitSuccess })'

Could you give me a hint? Thanks

+3
source share
2 answers

You have an extra >>(or optional do) on line 13:

_ -> do putStrLn ("Run this way: ./projekt inputFile RE") >>

it should be:

_ -> do putStrLn ("Run this way: ./projekt inputFile RE")

or

_ -> putStrLn ("Run this way: ./projekt inputFile RE") >> exitFailure

Full code:

main = do
l@(x:xs) <- getArgs
case length l of
    2 -> do catch (readFile x) $ \_ -> do
            putStrLn $ "Error on reading file: " ++ x
            getLine
            exitWith ExitSuccess
    _ -> do putStrLn $ "Run this way: ./projekt inputFile RE"
            exitFailure
+3
source

Check the indentation.

Although your code looks like this, as you put in, the error message indicates that perhaps getLineand exitWith ExitSuccessare indented, located higher than the putStrLnabove. Perhaps this is a problem with -v-tabs spaces?

0
source

All Articles