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
+6.9k Swift : Convert (cast) String to Float
+9.5k Golang : Get currencies exchange rates example
+18.5k Golang : Set or Add HTTP Request Headers
+11.3k Golang : zlib compress file example
+3.8k Golang : Calculate a pip value and distance to target profit example
+30.3k Golang : Copy directory - including sub-directories and files
+9.1k Golang : Resolve domain name to IP4 and IP6 addresses.
+13.8k Golang : Find location by IP address and display with Google Map
+21k Golang : How to read JPG(JPEG), GIF and PNG files ?
+17.6k Golang : Read input from console line
+6.9k Golang : Multiplexer with net/http and map
+12.8k Golang : ROT47 (Caesar cipher by 47 characters) example