Skip to content

Instantly share code, notes, and snippets.

@meson10
Created July 18, 2015 20:00
Show Gist options
  • Save meson10/d56eface6f87c664d07d to your computer and use it in GitHub Desktop.
Save meson10/d56eface6f87c664d07d to your computer and use it in GitHub Desktop.
If you observe, In case of panic recovery you can only prevent the function from crashing at exit.
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)
g(2)
g(3)
g(1)
fmt.Println("Returned normally from g.")
}
func g(i int) {
if i == 3 {
fmt.Println("Panicking!")
panic(fmt.Sprintf("%v", i))
} else {
fmt.Println("Printing in g", i)
}
defer fmt.Println("Defer in g", i)
}
@meson10
Copy link
Author

meson10 commented Jul 18, 2015

Output:

piyush:~ [] $ go run /tmp/test.go 
Calling g.
Printing in g 0
Defer in g 0
Printing in g 2
Defer in g 2
Panicking!
Recovered in f 3
Returned normally from f.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment