Golang : Exit, terminating or aborting a program
There are times where a controlled termination of a program is required rather than proceeding ahead. This is a quick example on how to exit/terminating/aborting a program in Golang.
package main
import (
"fmt"
"os"
)
func main() {
// will not be executed because of defer causing to Exit happen before this line
defer fmt.Println("Doing something...")
fmt.Println("Oh no, fatal error!")
os.Exit(1)
}
Sample output :
go run exit.go
Oh no, fatal error!
exit status 1
If the program is compiled, there WILL BE NO exit status number.
go build exit.go
./exit
Oh no, fatal error!
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+3.8k Linux/MacOSX : How to symlink a file?
+14.8k Golang : Delete files by extension
+7.5k Golang : How to join strings?
+10.8k Golang : Print UTF-8 fonts on image example
+42.6k Golang : Use wildcard patterns with filepath.Glob() example
+12.6k Golang : How to determine if a year is leap year?
+6.3k Golang : How to stop user from directly running an executable file?
+16.7k Golang : Get command line arguments
+22.8k Golang : Daemonizing a simple web server process example
+28.9k Golang : Generate random string
+21.7k Golang : Randomly pick an item from a slice/array example
+7.2k Golang : Check if integer is power of four example