您的位置:首页 > 健康 > 养生 > go panic

go panic

2024/10/6 10:28:43 来源:https://blog.csdn.net/2401_82869454/article/details/139126915  浏览:    关键词:go panic

panic 能够改变程序的控制流,调用 panic 后会立刻停止执行当前函数的剩余代码,并在当前 goroutine 中递归执行调用方的 defer。

// A _panic holds information about an active panic.
//
// A _panic value must only ever live on the stack.
//
// The argp and link fields are stack pointers, but don't need special
// handling during stack growth: because they are pointer-typed and
// _panic values only live on the stack, regular stack pointer
// adjustment takes care of them.
type _panic struct {argp      unsafe.Pointer // pointer to arguments of deferred call run during panic; cannot move - known to liblinkarg       any            // argument to paniclink      *_panic        // link to earlier panicpc        uintptr        // where to return to in runtime if this panic is bypassedsp        unsafe.Pointer // where to return to in runtime if this panic is bypassedrecovered bool           // whether this panic is overaborted   bool           // the panic was abortedgoexit    bool
}

panic:

  1. 创建新的 panic函数并添加到所在 goroutine 的 _panic 链表的最前面。
  2. 在循环中不断从当前 goroutine 的 _defer 中链表获取 defer函数并调用执行。
  3. 调用 runtime.fatalpanic 中止整个程序。
    runtime.fatalpanic 实现了无法被恢复的程序崩溃:
  4. 它在中止程序之前会通过 runtime.printpanics 打印出全部的 panic 消息以及调用时传入的参数。
  5. 打印崩溃消息后会调用 runtime.exit 退出当前程序并返回错误码 2,程序的正常退出也是通过 runtime.exit 实现的。

panic() 会退出进程,是因为调用了 exit 的系统调用。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com