[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
2
3
4
5
func Exit(code int)

Exit causes the current program to exit with the given status code.
Conventionally, code zero indicates success, non-zero an error.
The program terminates immediately; deferred functions are not run.

Key points:


  1. The program terminates immediately with a non-zero status.

  2. deferred functions are not run.


Example: main.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Use `os.Exit` to immediately exit with a given
// status.

package main

import (
"log"
"os"
)

func main() {

// `defer`s will _not_ be run when using `os.Exit`, so
// this `log.Println` will never be called.
defer log.Println("!")

// Exit with status 3.
os.Exit(3)
}

// Note that unlike e.g. C, Go does not use an integer
// return value from `main` to indicate exit status. If
// you'd like to exit with a non-zero status you should
// use `os.Exit`.

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
2
$ go run main.go
Program exited: status 3.

log.Fatal(v …interface{})

Let’s see function definition.

1
2
3
4
5
6
7
8
func Fatal(v ...interface{})
Fatal is equivalent to Print() followed by a call to os.Exit(1).

func Fatalf(format string, v ...interface{})
Fatalf is equivalent to Printf() followed by a call to os.Exit(1).

func Fatalln(v ...interface{})
Fatalln is equivalent to Println() followed by a call to os.Exit(1).

Key points:


  1. Print a given message.

  2. The program terminates immediately with a non-zero status.

  3. deferred functions are not run.


Example: main.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Use `log.Fatal` to immediately exit with a given message.

package main

import (
"log"
)

func main() {

// `defer`s will _not_ be run when using `log.Fatal`, so
// this `log.Println` will never be called.
defer log.Println("!")

// Fatal with with a given message.
log.Fatal("Fatal")
}

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
2
3
4
$ go run main.go
2009/11/10 23:00:00 Fatal

Program exited: status 1.

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

[4] The Go Programming Language - https://golang.org/