Secure connection in the Golang

When I open a socket connection, I immediately add the socket.Close () logic to the snooze function after opening the socket. However, what if socket.Close () causes another panic? Should I always stack another deferred / restore inside the external deferral to prevent my program from crashing? Something like this: http://play.golang.org/p/GnEMQS-0jj

Thanks Elgs

+7
go panic
source share
1 answer

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.

+7
source share

All Articles