Cookies management by TermsFeed Cookie Consent

๐Ÿ›‘ Exit an app in Go

shorts introduction os

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()?

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.


Thank you for being on our site ๐Ÿ˜Š. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

๐Ÿพ How to compare strings in Go

shorts introduction strings

๐Ÿค Create a new file in Go

shorts introduction file

๐Ÿงน Delete or remove a file in Go

shorts introduction file