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 Golang : Generate human readable password
+9.4k Golang : Decompress zlib file example
+9.5k Swift : Convert (cast) Float to String
+3.1k Nginx and PageSpeed build from source CentOS example
+7.6k Golang : Print how to use flag for your application example
+15.4k Golang : Get command line arguments
+9.9k Swift : Convert (cast) Int or int32 value to CGFloat
+10.3k Golang : Count number of runes in string
+11.2k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+5.2k Golang : How to stop user from directly running an executable file?
+4.5k PHP : How to check if an array is empty ?
+4.7k Restart Apache or Nginx web server without password prompt