一. panic

  • panic是builtin中函数
  1. // The panic built-in function stops normal execution of the current
  2. // goroutine. When a function F calls panic, normal execution of F stops
  3. // immediately. Any functions whose execution was deferred by F are run in
  4. // the usual way, and then F returns to its caller. To the caller G, the
  5. // invocation of F then behaves like a call to panic, terminating G's
  6. // execution and running any deferred functions. This continues until all
  7. // functions in the executing goroutine have stopped, in reverse order. At
  8. // that point, the program is terminated and the error condition is reported,
  9. // including the value of the argument to panic. This termination sequence
  10. // is called panicking and can be controlled by the built-in function
  11. // recover.
  12. func panic(v interface{})
  • panic有点类似与其他编程语言的throw,抛出异常.当执行到panic后终止剩余代码执行.并打印错误栈信息
  1. func main() {
  2. fmt.Println("1")
  3. panic("panic执行了,哈哈")
  4. fmt.Println("2")
  5. }
  • 执行结果
  1. 1
  2. panic: panic执行了,哈哈
  3. goroutine 1 [running]:
  4. main.main()
  5. D:/gowork/c/main.go:7 +0x80
  • 注意panic不是立即停止程序(os.Exit(0)),defer还是执行的.
  1. func main() {
  2. defer func(){
  3. fmt.Println("defer执行")
  4. }()
  5. fmt.Println("1")
  6. panic("panic执行了,哈哈")
  7. fmt.Println("2")
  8. }