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
+7.2k Golang : Not able to grep log.Println() output
+10.6k Golang : Simple File Server
+10.5k Golang : How to delete element(data) from map ?
+48k Golang : How to convert JSON string to map and slice
+10.2k Golang : cannot assign type int to value (type uint8) in range error
+7.3k Golang : Individual and total number of words counter example
+23.4k Golang : Check if element exist in map
+11k How to test Facebook App on localhost ?
+16k Golang : Generate universally unique identifier(UUID) example
+16.4k Golang : Check if a string contains multiple sub-strings in []string?
+22.6k Golang : Strings to lowercase and uppercase example
+12k Golang : Save webcamera frames to video file