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
+12.4k Golang : Encrypt and decrypt data with x509 crypto
+15.9k Golang : Get current time from the Internet time server(ntp) example
+11.3k Golang : Characters limiter example
+11.7k Golang : Calculations using complex numbers example
+6.9k Golang : Decode XML data from RSS feed
+4.7k Chrome : How to block socketloop.com links in Google SERP?
+16.4k Golang : Convert slice to array
+9.2k Golang : How to check if a string with spaces in between is numeric?
+8.1k Golang : Check from web if Go application is running or not
+7.5k Golang : How to stop user from directly running an executable file?
+51.4k Golang : Check if item is in slice/array
+5.7k Golang : Error handling methods