Skip to content

Instantly share code, notes, and snippets.

@se77en
Created April 4, 2014 08:36
Show Gist options
  • Save se77en/9970559 to your computer and use it in GitHub Desktop.
Save se77en/9970559 to your computer and use it in GitHub Desktop.
go with try catch
package main
import "fmt"
type panique interface{}
type catch struct {
cause panique
}
func (c catch) Catch(f func(panique)) {
if c.cause != nil {
f(c.cause)
}
}
func Try(f func()) (c catch) {
defer func() {
c.cause = recover()
}()
f()
return c
}
func main() {
Try(func() {
fmt.Println("nothing to see here")
}).Catch(func(p panique) {
fmt.Println("this won't be printed, since there's no panic")
})
Try(func() {
panic("oops")
}).Catch(func(p panique) {
fmt.Printf("keep calm and panic: %v", p)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment