When to use os.Exit() and panic()?

后端 未结 3 1021
一个人的身影
一个人的身影 2020-12-12 16:48

Could someone explain the key differences between os.Exit() and panic() and how they are used in practice in Go?

3条回答
  •  执笔经年
    2020-12-12 17:40

    First of all, os.Exit() can be used to exit the program normally without an error, and panic not, so that's one key distinction. Another is that panic somewhere can be caught and ignored or logged using recover.

    But if we're talking about an erroneous exit code, let's say:

    Use panic when something goes horribly wrong, probably a programmer error that should have been caught before going to production. This is why it prints the stack.

    Use os.Exit(errorCode) or something like that if you want to:

    1. control the exit code of the program for scripting purposes.

    2. want an orderly exit on an error that is expected (e.g user input error).

    So basically panic is for you, a bad exit code is for your user.

提交回复
热议问题