Recover from panic in Go

Posted by yhuang
Public (Editable by Users)
Go
Edit
package main

import (
	"fmt"
)

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

	badFunction()
	fmt.Println("We didn't exit")

	panic("failed in main")
}

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

	panic("failed in function")
}