go语言实践笔记

Posted by onceme on Monday, December 3, 2018

TOC

  • 使用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.")
    }
    

comments powered by Disqus
Ï