Skip to content

Instantly share code, notes, and snippets.

@ijt
Created May 24, 2011 07:02
Show Gist options
  • Save ijt/988242 to your computer and use it in GitHub Desktop.
Save ijt/988242 to your computer and use it in GitHub Desktop.
Example of exception handling in Go
// Exception handling example, fleshed out from Rob Pike's post
// at http://goo.gl/ZiUra
package main
import "fmt"
func f(dopanic bool) {
defer func() {
if x := recover(); x != nil {
fmt.Printf("panicking with value %v\n", x)
panic(x) // go back to panicking
}
fmt.Printf("function returns normally\n")
}()
fmt.Printf("before\n")
p(dopanic)
fmt.Printf("after\n")
}
func p(dopanic bool) {
if dopanic {
panic(3)
}
}
func main() {
fmt.Printf("Calling f(false)\n")
f(false)
fmt.Printf("\n\n")
fmt.Printf("Calling f(true)\n")
f(true)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment