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
+10k Golang : Intercept and process UNIX signals example
+10.1k Golang : How to pipe input data to executing child process?
+13.8k Golang : How to check if IP address is in range
+12.2k Golang : error parsing regexp: invalid or unsupported Perl syntax
+14.8k Golang : Read a file line by line
+6.8k Golang : Ways to recover memory during run time.
+4.9k Golang : Launching your executable inside a console under Linux
+5.8k Golang : Get expvar(export variables) to work with multiplexer
+13.8k Golang : Get HTTP protocol version example
+6k Golang : How to call function inside template with template.FuncMap
+11.4k Elastic Search : Return all records (higher than default 10)