go语言实践笔记

  • 使用recover()捕捉panic时,只能捕捉直接调用的方法,通过go命令调用的代码块中抛出的panic,则无法捕捉
    package main

import ( "fmt" "errors" )

func main() { fmt.Println("Enter function main.") defer func(){ fmt.Println("Enter defer function.") if p := recover(); p != nil { fmt.Printf("panic: %s\n", p) } fmt.Println("Exit defer function.") }() // 引发 panic。 go func() { panic(errors.New("something wrong")) }() fmt.Println("Exit function main.") }

This article is my 19th oldest. It is 48 words long