Skip to content

Instantly share code, notes, and snippets.

@se77en se77en/try_catch.go
Created Apr 4, 2014

Embed
What would you like to do?
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
You can’t perform that action at this time.