mchirico / zDaily

Playground to hack and test ideas with Zoe
1 stars 2 forks source link

Day 34: Recover #38

Open mchirico opened 3 years ago

mchirico commented 3 years ago

Recover from Go Panic

Ref: recover

package main

import "fmt"

func main() {
    f()
    fmt.Println("Returned normally from f.")
}

func f() {
    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 > 3 {
        fmt.Println("Panicking!")
        panic(fmt.Sprintf("%v", i))
    }
    defer fmt.Println("Defer in g", i)
    fmt.Println("Printing in g", i)
    g(i + 1)
}
tacomonkautobot[bot] commented 3 years ago

mchirico, Thanks for opening this issue!