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
+20.4k Golang : How to get struct tag and use field name to retrieve data?
+6.1k Golang : Use NLP to get sentences for each paragraph example
+8.5k Golang : Check if integer is power of four example
+7.9k Gogland : Where to put source code files in package directory for rookie
+9k Golang : On lambda, anonymous, inline functions and function literals
+8.4k Golang : Qt splash screen with delay example
+11.7k Get form post value in Go
+9.3k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+11k Golang : Sieve of Eratosthenes algorithm
+15.5k Golang : Delete certain files in a directory
+7.1k Nginx : Password protect a directory/folder
+19.3k Mac OSX : Homebrew and Golang