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
+8.9k Golang : GMail API create and send draft with simple upload attachment example
+26.8k Golang : Convert file content into array of bytes
+5.2k Golang : Experimental Jawi programming language
+8k Golang : Trim everything onward after a word
+27.7k PHP : Convert(cast) string to bigInt
+10.7k Android Studio : Simple input textbox and intercept key example
+11.4k Golang : How to flush a channel before the end of program?
+6.1k nginx : force all pages to be SSL
+30.1k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+9.9k Golang : ffmpeg with os/exec.Command() returns non-zero status
+22.8k Golang : Round float to precision example
+10k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral