Safe close connection in Golang
Asked Answered
M

1

11

When I open a socket connection, I immediately put the socket.Close() logic in a defer function after the opening of the socket. However, what if the socket.Close() would cause another panic? Should I always nest another defer/recover inside the outer defer to prevent my program from crashing? Something like this: http://play.golang.org/p/GnEMQS-0jj

Thanks, Elgs

Minnaminnaminnie answered 10/12, 2013 at 13:22 Comment(4)
socket.Close() cannot cause a panic IIRC.Yul
I am not perfectly sure: Close (on e.g. a net.TCPConn) may result in an error but I think it doesn't panic. And if it panics, e.g. due to hardware corruption or out of memory your app is blown anyway. Depending on your case you might want to handle the returned error, but handling a panic in Close seems a bit paranoid.Expiation
@FUZxxl when I try to close a client socket which is refused to connect by the server, it panics. Is there any way to tell if a socket is safe to close without panicking. Or do I have to nest one more level of defer just for the socket close logic.Minnaminnaminnie
@ElgsQianChen This looks like a bug in Go. Please report a bug at the Go bugtracker.Yul
V
11

Generally you don't need to worry much about panics. They usually represent two classes of errors: developer mistakes (nil references, array out of bounds) and system level errors you probably can't do much about (like running out of memory).

As others said socket.Close will not panic, rather it returns an error. If you do:

defer socket.Close()

The error is discarded and you don't need to do anything else.

But suppose you did want to recover from a panic. If you're recovery handler is deferred first then you don't need to do anything else:

func main() {
  defer func() {
    if err := recover(); err != nil {
      fmt.Println(err)
    }
  }()
  defer panic("this will be recovered")
}

Deferred functions are run in reverse order: http://golang.org/ref/spec#Defer_statements

Deferred functions are executed immediately before the surrounding function returns, in the reverse order they were deferred.

Volumeter answered 10/12, 2013 at 23:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.