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.4k Golang : Secure file deletion with wipe example
+5.1k Golang : Missing Subversion command
+7.7k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+10.8k Golang : Save webcamera frames to video file
+7.9k Golang : automatically figure out array length(size) with three dots
+7.8k Golang : Capture text return from exec function example
+11.8k Golang : Convert IPv4 address to packed 32-bit binary format
+5k Linux/MacOSX : Search for files by filename and extension with find command
+10.7k Golang : Perform sanity checks on filename example
+13.1k Golang : How to get URL port?
+15.4k Golang : How to implement two-factor authentication?
+17.7k Golang : Calculate entire request body length during run time