Fragment Description:

Two built-in Go functions:
Recover and Panic.
an example by the Golang authors that is worthwhile revisiting.
Panic is a built-in function that stops the ordinary flow of control and begins panicking.
Recover is a built-in function that regains control of a panicking goroutine.
Recover is only useful inside deferred functions.


Go Playground

Last update, on 2015, Fri 9 Oct, 16:15:33

/* ... <== see fragment description ... */

package main

import "fmt"

func main() {
    fmt.Println("Returned normally from f.")
func f() {
    // remove from f() the defer func() lines to see what is occurring
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered in f", r)
    fmt.Println("Calling g.")
    fmt.Println("Returned normally from g.")
func g(i int) {
    if i >= 4 {
        panic(fmt.Sprintf("panic here: %v", i))
    defer fmt.Println("Defer in g", i)
    fmt.Printf("Printing in g, run[%d]: \n", i)
    // a recursion that could easily become infinite
    g(i + 1)

/* Expected Output:
Calling g.
Printing in g, run[0]:
Printing in g, run[1]:
Printing in g, run[2]:
Printing in g, run[3]:
Defer in g 3
Defer in g 2
Defer in g 1
Defer in g 0
Recovered in f panic here: 4
Returned normally from f.