Last active
September 14, 2015 10:05
-
-
Save nbari/e9d78d7ac8639cd4914b to your computer and use it in GitHub Desktop.
recover from panic within Goroutines
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
// The 'recovery' part of a panic has to happen on the same goroutine as the | |
// panic itself, otherwise it bubbles to the top without being captured. so it | |
// needed to be "attached" to the same thing that called foo, which was your | |
// anonymous func the recovery itself is a deferred anonymous func and if it | |
// feels difficult to use, then that's excellent. you shouldn't be using this, | |
// and should avoid code that does 'neat' things in this direction | |
package main | |
import "fmt" | |
import "time" | |
func foo() { | |
panic("no recovery") | |
} | |
func main() { | |
go func() { | |
defer func() { | |
if r := recover(); r != nil { | |
fmt.Println("recovered") | |
} | |
}() | |
foo() | |
}() | |
<-time.After(10 * time.Second) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment