dongpo1599 2013-09-23 16:09
浏览 83
已采纳

用错误代码退出吗?

What's the idiomatic way to exit a program with some error code?

The documentation for Exit says "The program terminates immediately; deferred functions are not run.", and log.Fatal just calls Exit. For things that aren't heinous errors, terminating the program without running deferred functions seems extreme.

Am I supposed to pass around some state that indicate that there's been an error, and then call Exit(1) at some point where I know that I can exit safely, with all deferred functions having been run?

  • 写回答

5条回答 默认 最新

  • doulou1970 2013-09-23 22:30
    关注

    I do something along these lines in most of my real main packages, so that the return err convention is adopted as soon as possible, and has a proper termination:

    func main() {
        if err := run(); err != nil {
            fmt.Fprintf(os.Stderr, "error: %v
    ", err)
            os.Exit(1)
        }
    }
    
    func run() error {
        err := something()
        if err != nil {
            return err
        }
        // etc
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办