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
+10.8k Golang : List objects in AWS S3 bucket
+5.6k Golang : Shuffle strings array
+28.6k Golang : Validate email address with regular expression
+14.8k Golang : [json: cannot unmarshal object into Go value of type]
+11.3k Golang : Save(pipe) HTTP response into a file
+12.1k Golang : How to shuffle elements in array or slice?
+15k Golang : Get command line arguments
+7.2k Golang : Go as a script or running go with shebang/hashbang style
+3.4k Javascript : Change page title to get viewer attention
+9.1k Golang : Display list of countries and ISO codes
+6.9k Golang : Take screen shot of browser with JQuery example
+17.1k Golang : Generate MD5 checksum of a file