Recover from a Panic

How to catch a panic error when it’s thrown? That’s what this post hopes to answer.

Go has a built in recover() function which allows you to pick up and run some code when a panic is thrown. This can be useful for regaining execution of your program, or allowing the panic to happen, but to clean up state (like files) before your program closes.

If you are curious what the structure of a panic is, see it’s docs here.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import "fmt"

func main() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("Recovered from", r)
		}
	}()

	causePanic()  // This function will cause a panic
}

func causePanic() {
	panic("eek!")
}

We use defer to run a function after main has completed. In our example we have it in main, but you can catch a panic within a specific function by using the same idea. We then use recover to get the panic, and in our example print it to screen.

Example In Action

recover from panic example