Fragment Description:



Two built-in Go functions:
Recover and Panic.
Recover/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.


deferPanicRecover

Go Playground

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

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

package main

import "fmt"

func main() {
    f()
    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.")
    g(0)
    fmt.Println("Returned normally from g.")
}
func g(i int) {
    if i >= 4 {
        fmt.Println("Panicking!")
        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]:
Panicking!
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.
*/



Comments