As a rule, you do not need to worry about panic. They usually represent two classes of errors: developer errors (references to nil, an array outside the boundaries) and errors at the system level, which you probably cannot do much (for example, run out of memory).
As others have said, socket.Close will not panic; rather, it returns an error. If you do:
defer socket.Close()
The error is discarded and you do not need to do anything.
But suppose you really wanted to recover from a panic. If the recovery handler is delayed first, then you do not need to do anything:
func main() { defer func() { if err := recover(); err != nil { fmt.Println(err) } }() defer panic("this will be recovered") }
Deferred functions are performed in the reverse order: http://golang.org/ref/spec#Defer_statements
The deferred functions are executed immediately before the return of the surrounding function; in the reverse order, they are deferred.
Caleb
source share