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
+5.3k Golang : Experimental emojis or emoticons icons programming language
+7k Golang : Get final or effective URL with Request.URL example
+13.3k Golang : How to shuffle elements in array or slice?
+12.1k Golang : Image to ASCII art example
+29.9k Golang : Convert an image file to []byte
+7.7k Golang : Gaussian blur on image and camera video feed examples
+4.6k How to check with curl if my website or the asset is gzipped ?
+24.5k Golang : How to write CSV data to file
+40.2k Golang : Convert string to array/slice
+12.6k Golang : How to check if a file is hidden?
+3.9k Golang : Calculate a pip value and distance to target profit example
+18.3k Golang : Convert seconds to human readable time format example