英文:
Safe close connection in Golang
问题
当我打开一个套接字连接时,我立即在套接字打开后的延迟函数中放置了socket.Close()的逻辑。然而,如果socket.Close()会引发另一个panic,我应该总是在外部延迟函数中嵌套另一个defer/recover来防止程序崩溃吗?类似这样的做法:http://play.golang.org/p/GnEMQS-0jj
谢谢,
Elgs
英文:
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
答案1
得分: 11
通常情况下,你不需要过多担心恐慌。它们通常代表两类错误:开发者的错误(空引用、数组越界)和系统级错误,你可能无法做太多处理(比如内存耗尽)。
正如其他人所说,socket.Close
不会引发恐慌,而是返回一个错误。如果你这样做:
defer socket.Close()
错误会被丢弃,你不需要做其他操作。
但是假设你确实想要从恐慌中恢复。如果你的恢复处理程序是被延迟执行的,那么你不需要做其他操作:
func main() {
defer func() {
if err := recover(); err != nil {
fmt.Println(err)
}
}()
defer panic("this will be recovered")
}
延迟函数按相反的顺序执行:http://golang.org/ref/spec#Defer_statements
延迟函数会在包围它的函数返回之前立即执行,按照被延迟的顺序执行。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论