Is it good to use log.Panic instead of log.Fatal?

Let’s consider this situation:

func main() {
	file1, err := os.Open("file1");
	if err != nil {
		log.Fatalln(err)
	}
	defer file1.Close()
	
	// What happens if this fail?
	file2, err := os.Open("file2");
	if err != nil {
		log.Fatalln(err)
	}
	defer file2.Close();
}

The problem with the previous code is that, if the application fails to open “file2”, the first file won’t be closed, since log.Fataln exits immediately from the program and does not execute the “defer” functions. But the previous code can be fixed easily by using log.Panic.

What do you think? Is it good to use log.Panic instead of log.Fatal?

Your observation is correct:

Fatalln is equivalent to Println() followed by a call to os.Exit(1).

And for os.Exit:

The program terminates immediately; deferred functions are not run.

So I agree that os.Fatalln is a bad choice.

See also this blog:

https://blog.golang.org/defer-panic-and-recover

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.