I recently learned that when we call log.Fatal which exist the program using os.Exit function, any code in defer will not be executed.

Example

https://play.golang.org/p/3IvenLd3hBh
  • go
1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import (
	"log"
)

func main() {
	defer func() {
		log.Printf("Hello, playground")
	}()

	log.Printf("fatal error")
}

This code will print below output:

2009/11/10 23:00:00 fatal error
2009/11/10 23:00:00 Hello, playground

But, if we change line 12 to instead use log.Fatal then the defer function will not execute.

https://play.golang.org/p/iOgXCUp8T74
  • go
1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import (
	"log"
)

func main() {
	defer func() {
		log.Printf("Hello, playground")
	}()

	log.Fatal("fatal error")
}

This code will print below output:

2009/11/10 23:00:00 fatal error