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
+13.8k Golang : Human readable time elapsed format such as 5 days ago
+7.3k Golang : How to detect if a sentence ends with a punctuation?
+21.7k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+26.5k Golang : Encrypt and decrypt data with AES crypto
+24.4k Golang : GORM read from database example
+8.3k Golang : Implementing class(object-oriented programming style)
+8.1k Golang : Tell color name with OpenCV example
+6.2k Golang : How to get capacity of a slice or array?
+6k Fontello : How to load and use fonts?
+19k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+7k Golang : Squaring elements in array
+5.3k Golang : What is StructTag and how to get StructTag's value?