Could someone explain the key differences between os.Exit()
and panic()
and how they are used in practice in Go?
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:
control the exit code of the program for scripting purposes.
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.