我正在尝试调用用户系统上可能存在或可能不存在的进程。如果命令不存在,我想通过一个不同的命令,但我无法弄清楚如何做到这一点。我尝试了以下代码的许多变体:
-- call.hs
import System.Process
import System.Exit
main = do
(_,_,_,p) <- createProcess (proc "this_command_does_not_exist" [])
ExitFailure _ <- waitForProcess p
-- This line is never printed:
putStrLn "The command failed"
当我使用runghc call.hs
运行时,我得到以下输出:
call.hs: this_command_does_not_exist: createProcess: does not exist (No such file or directory)
表示程序终止于该行并且不会继续。我该如何处理这个错误?
答案 0 :(得分:1)
您可以使用Control.Exception
中的try
来捕获程序不存在时引发的IOException
:
import Control.Exception
-- we specialize the signature of "try" to catch only IOException
try' :: IO a -> IO (Either IOException a)
try' = try
main = do
result <- try' $ createProcess (proc "this_command_does_not_exist" [])
case result of
Left ex -> putStrLn $ "error starting: " ++ show ex
Right (_,_,_,p) -> putStrLn "started ok"