Haskell - readFile捕获异常

时间:2011-03-07 21:31:21

标签: exception haskell exception-handling io readfile

我正在尝试在Haskell中读取文件但异常捕获但无法正常工作。 代码如下:

     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

我收到了这个错误:

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 })'
你能给我一个暗示吗? 感谢

2 个答案:

答案 0 :(得分:3)

第13行还有一个额外的>>(或额外的do):

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

应该是:

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

或:

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

完整代码:

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

答案 1 :(得分:0)

检查缩进。

尽管您的代码在粘贴时看起来没问题,但错误消息表明getLineexitWith ExitSuccess可能比上面的putStrLn缩进。也许这是一个空格-v-标签问题?