Created
April 4, 2014 08:36
-
-
Save se77en/9970559 to your computer and use it in GitHub Desktop.
go with try catch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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