Exit an Application, With or Without an Error Code

· 257 words · 2 minutes read

Exiting an application in Go happens anyway when the main() function is complete, but the purpose of this post is to show you how to force that to happen. Perhaps at an earlier stage than the end of your code, perhaps with an error code too. This is a well established method in POSIX systems, whereby a program can return a 0-255 integer to indicate if the program ran successfully, and if not, why not.

We’ll be using the os package in stdlib to exit for us. First we’ll look at exiting the application successfully (just below), then we’ll look at exiting with an error code.

Exit Successfully

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println("Hello World")

	// Exit successfully
	os.Exit(0)

	// Never runs
	fmt.Println("Something else...")
}

exit successfully from an application

Exit with Error (Status 1+)

Specifying an exit code above zero usually means an error has occurred. There is a list of common/reserved exit codes for bash to keep an eye on, but in our example below we will just be using our generic error code of 1.

Some common codes:

Code Meaning
1 General error
2 Misuse of shell builtins
127 Command not found
128 Fatal error signal
130 Ctrl+C termination
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println("Exits with status code 1")

	// Status Code 1 = Catchall for general errors
	os.Exit(1)
}

exit with an error from an application

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!