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.8k CloudFlare : Another way to get visitor's real IP address
+9.6k Golang : Replace a parameter's value inside a configuration file example
+9.9k Android Studio : Create custom icons for your application example
+8.1k Golang : Generate Codabar
+14.8k Golang : Generate universally unique identifier(UUID) example
+2.2k Golang : Switch Redis database redis.NewClient
+6.8k Swift : Convert (cast) String to Double
+9.3k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+5.4k Golang : Test input string for unicode example
+12.3k Golang : Get dimension(width and height) of image file
+11.7k Python : Convert IPv6 address to decimal and back to IPv6
+36k Golang : Read a text file and replace certain words