[Awesome Go] Use os.Exit, log.Fatal to terminate program - os.Exit - log.Fatal - errors - Programming Language - Golang (Go) - Exception Error Handling
os.Exit(int), log.Fatal(v …interface{})
In Go language you can terminate program with os.Exit
or log.Fatal
to handle errors.
os.Exit(int)
Let’s see function definition.
1 | func Exit(code int) |
Key points:
-
The program terminates immediately with a non-zero status.
-
deferred functions are not run.
Example: main.go
1 | // Use `os.Exit` to immediately exit with a given |
If you run exit.go using go run, the exit will be picked up by go and printed.
Note that the ! from our program never got printed.
1 | go run main.go |
log.Fatal(v …interface{})
Let’s see function definition.
1 | func Fatal(v ...interface{}) |
Key points:
-
Print a given message.
-
The program terminates immediately with a non-zero status.
-
deferred functions are not run.
Example: main.go
1 | // Use `log.Fatal` to immediately exit with a given message. |
If you run exit.go using go run, the exit will be picked up by go and printed.
Note that the ! from our program never got printed.
1 | go run main.go |
References
[1] Go by Example: Exit - https://gobyexample.com/exit
[2] log - The Go Programming Language - https://golang.org/pkg/log/#Fatalln
[3] os - The Go Programming Language - https://golang.org/pkg/os/#Exit