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