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.6k Python : Convert(cast) bytes to string example
+5.8k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+14.3k Golang : Find file size(disk usage) with filepath.Walk
+6.8k Golang : Apply Histogram Equalization to color images
+4.3k List of Golang XML tutorials
+3.2k Chrome : How to block socketloop.com links in Google SERP?
+9.1k Golang : Sort and reverse sort a slice of runes
+12.2k Golang : How to check if IP address is in range
+11.7k Golang : Overwrite previous output with count down timer
+7.8k Golang : Resumable upload to Google Drive(RESTful) example
+22.3k Golang : Call function from another package
+12k Golang : How to filter a map's elements for faster lookup