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.8k Web : How to see your website from different countries?
+31.1k Golang : Get local IP and MAC address
+9.1k Golang : Terminate-stay-resident or daemonize your program?
+5.5k Golang : Struct field tags and what is their purpose?
+34.2k Golang : Smarter Error Handling with strings.Contains()
+7.5k Golang : get the current working directory of a running program
+4.8k Swift : Convert (cast) Float to Int or Int32 value
+5.6k Linux : Disable and enable IPv4 forwarding
+9.2k Golang : How to extract video or image files from html source code
+13.5k Golang : unknown escape sequence error
+16.1k Golang : Send email and SMTP configuration example
+33.3k Golang : All update packages with go get command