When to use os.Exit () and panic () in the Golang?

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

+49
go exit
Feb 12 '15 at 8:45
source share
2 answers

First of all, whenever you have a question โ€œhow is it used in practiceโ€, a good way to start is to search the Go source code (or any sufficiently large base code), and docs for the answers.

Now os.Exit and panic very different. panic used when a program or part of it has reached a state that cannot be restored.

When panic is called, including implicitly at runtime errors, such as indexing a slice out of bounds or rejecting a type assertion, it immediately stops the execution of the current function and starts expanding the goroutine stack, launching any pending functions along the way. If this unwind reaches the top of the goroutine stack, the program dies.

os.Exit used when you need to immediately stop executing a program, without the possibility of restoring or executing a pending cleanup statement, and also return an error code (which other programs can use to report what happened). This is useful in tests, when you already know that after this one test will fail, the other will also fail, so you can just exit. It can also be used when your program has done everything you need, and now you just need to exit, i.e. After printing a help message.

In most cases, you will not use panic (you should return error instead), and you almost never need os.Exit outside of some cases in tests and to quickly os.Exit the program.

+45
Feb 12 '15 at 9:08
source share

First of all, os.Exit() can be used to exit the program, as a rule, without errors, and there is no panic, so there is one key difference. Another is that a panic somewhere can be caught and ignored or registered with recover .

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

Use panic when something goes horribly wrong, perhaps a programmer error that you should catch before starting production. That's why it prints a stack.

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

  • manage the exit code of the scripting program.

  • an ordered exit from the expected error is required (for example, a user input error).

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

+42
Feb 12 '15 at 9:05
source share



All Articles