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

后端 未结 3 1029
一个人的身影
一个人的身影 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:24

    The key differences are:

    1. os.Exit skips the execution of deferred function.
    2. With os.Exit, you can specify the exit code.
    3. panic is terminating while os.Exit is not. (Seems other answers do not mention this.)

    If you need to execute the deferred function, you have no choice but panic. (On the other hand, if you want to skip execution of deferred function, use os.Exit.)

    If a non-void function is defined in such a way:

    1. the function contains a lot of branches
    2. all branches are terminated with return or panic

    Then you cannot replace panic with os.Exit otherwise the compiler will refuse to compile the program, saying "missing return at end of function". (Go is very dumb here, even log.Panic does not terminate a function.)

    Under other conditions:

    1. Use panic when something really wired happens, e.g. programming logic error.
    2. Use os.Exit when you want an immediate exit, with specified exit code.

提交回复
热议问题