2011-03-07 46 views
3

我想读取Haskell中的文件,但捕获异常但无法正常工作。 代码如下:Haskell-readFile捕获异常

 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 })' 

你能不能给我一个提示? 感谢

+0

http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Control-Exception.html#5 – Jonke 2011-03-07 21:47:15

回答

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 
[email protected](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 
+0

非常感谢,问题是这个问题 – 2011-03-08 06:18:04

0

检查您的缩进。

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