Skip to content

Instantly share code, notes, and snippets.

@zeddee
Last active December 31, 2017 05:22
Show Gist options
  • Save zeddee/23a2dd515a9c9400655b91f75a8198ec to your computer and use it in GitHub Desktop.
Save zeddee/23a2dd515a9c9400655b91f75a8198ec to your computer and use it in GitHub Desktop.
// Attempting to write try-catch pattern
// with defer, panic, and recover in golang
// Built upon https://blog.golang.org/defer-panic-and-recover
package main
import "fmt"
func main() {
container()
fmt.Println("Try complete")
}
func container() {
// Only run recovery() when container() returns
// If recovery() is omitted, panic() exits the program and prints the stack trace
defer recov()
// Try for values of i = 0
fmt.Println("Trying")
tryer(0)
fmt.Println("Return normally from tryer")
}
func recov() {
if r := recover(); r != nil {
fmt.Println("Recovered in try", r)
}
}
func tryer(i int) {
// Panics (catches) for values where i > 3
if i > 3 {
fmt.Println("Panicking!")
panic(fmt.Sprintf("Panicking! %v", i))
}
// This executes when the current tryer() function returns
defer fmt.Println("Returning try no.", i)
fmt.Println("Values tried:",i)
// Recurse
// (Why not a loop?)
tryer(i+1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment