dongpi0658 2013-12-10 13:22
浏览 97
已采纳

Golang中的安全关闭连接

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条回答 默认 最新

  • doulvli9462 2013-12-10 23:01
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)