首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Haskell -使用指定的错误代码退出程序

Haskell -使用指定的错误代码退出程序
EN

Stack Overflow用户
提问于 2017-06-17 20:33:11
回答 2查看 2.2K关注 0票数 8

在Haskell中,有没有办法以指定的错误代码退出程序?我阅读的参考资料通常指向用于退出出现错误的程序的error函数,但它似乎总是以错误代码1结束程序。

代码语言:javascript
运行
复制
[martin@localhost Haskell]$ cat error.hs
main = do
    error "My English language error message"
[martin@localhost Haskell]$ ghc error.hs
[1 of 1] Compiling Main             ( error.hs, error.o )
Linking error ...
[martin@localhost Haskell]$ ./error 
error: My English language error message
[martin@localhost Haskell]$ echo $?
1
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-06-17 21:15:50

使用System.Exit中的exitWith

代码语言:javascript
运行
复制
main = exitWith (ExitFailure 2)

为了方便起见,我会添加一些助手:

代码语言:javascript
运行
复制
exitWithErrorMessage :: String -> ExitCode -> IO a
exitWithErrorMessage str e = hPutStrLn stderr str >> exitWith e

exitResourceMissing :: IO a
exitResourceMissing = exitWithErrorMessage "Resource missing" (ExitFailure 2)
票数 12
EN

Stack Overflow用户

发布于 2020-11-18 14:29:10

只允许出现错误消息的另一种方法是die

代码语言:javascript
运行
复制
import System.Exit

tests = ... -- some value from the program
testsResult = ... -- Bool value overall status

main :: IO ()
main = do
    if testsResult then
        print "Tests passed"
    else
        die (show tests)

接受的答案允许设置退出错误代码,因此它更接近问题的确切表达方式。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44604701

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档