To exit an application in Go, use the os.Exit()
function from the os
package. It causes the program to terminate immediately. The function takes a status code as an argument where the code zero indicates success and the non-zero an error.
The
os.Exit()
function terminates an app immediately, which means that if there are any deferred functions, they are not run.
Status codes
Typically, the status code 0
indicates an exit with no error, and 1
an exit with a general error. You can set the status code whatever you want, but keep in mind that some of them have special meanings, which you can check here.
Example
Exit with status code 0
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("Hello gosamples.dev")
os.Exit(0)
fmt.Println("Bye gosamples.dev")
}
Output:
Hello gosamples.dev
As you can see in the output, the app closes without any error immediately after calling the os.Exit()
. The last line of the main()
function is never executed.
Exit with status code 1
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("Hello gosamples.dev")
os.Exit(1)
fmt.Println("Bye gosamples.dev")
}
Output:
Hello gosamples.dev
exit status 1
When shutting down an application with a status code other than 0
, we see an additional message exit status <code>
in the output, indicating that the application is terminated with an error.
When to use os.Exit()
and when to use panic()
?
- The
os.Exit()
function terminates the program immediately with no possibility of recovery and running deferred functions. The app returns an error code that other programs can read to check what happened. - The
panic()
function is used to report unrecoverable errors in the program, for example, run-time errors such as indexing a slice out of bounds. It immediately stops the execution of the current function and starts to unwind the goroutine stack, running any deferred functions along the way. If that unwinding reaches the top of the goroutine’s stack, the program dies.
Typically, when your application reaches an unrecoverable state and cannot continue due to a specific error, you should use the panic()
function. With the panic()
, the application closes gracefully, all deferred functions are executed, and the application prints an accurate error message to the output. The os.Exit()
function, which closes the application immediately, can be used when you need from your application an error code that can be read by other scripts. It can also be used when your application has already done everything it should have done, and now it just needs to exit, such as after writing the results to the standard output or when the user runs a command to close the application.