在go例程中处理恐慌 [英] Handling panics in go routines

查看:336
本文介绍了在go例程中处理恐慌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解使用了处理紧急恢复的方法.但是当go例程出现恐慌时,以下块无法恢复

I understand that to handle panic recover is used. But the following block fails to recover when panic arises in go routine

func main() {
    done := make(chan int64)
    defer fmt.Println("Graceful End of program")
    defer func() {
     r := recover()
     if _, ok := r.(error); ok {
        fmt.Println("Recovered")
     }
    }()

    go handle(done)
    for {
        select{
        case <- done:
        return
        }
    } 
}

func handle(done chan int64) {
    var a *int64
    a = nil

    fmt.Println(*a)
    done <- *a
}

但是下面的块能够按预期执行

However following block is able to execute as expected

func main() {
    done := make(chan int64)
    defer fmt.Println("Graceful End of program")
    defer func() {
     r := recover()
     if _, ok := r.(error); ok {
        fmt.Println("Recovered")
     }
    }()

    handle(done)
    for {
        select{
        case <- done:
        return
        }
    } 
}

func handle(done chan int64) {
    var a *int64
    a = nil

    fmt.Println(*a)
    done <- *a
}

如何从go例程中出现的恐慌中恢复过来.这是游乐场的链接: https://play.golang.org/p/lkvKUxMHjhi

How to recover from panics that arise in go routines. Here is the link for playground : https://play.golang.org/p/lkvKUxMHjhi

推荐答案

仅当从与调用紧急情况相同的goroutine中调用恢复时,恢复才有效.

Recover only works when called from the same goroutine as the panic is called in. From the Go blog:

此过程将继续执行堆栈,直到当前的所有功能为止 goroutine已经返回,这时程序崩溃了

The process continues up the stack until all functions in the current goroutine have returned, at which point the program crashes

您必须在goroutine中进行延迟恢复.

You would have to have a deferred recover within the goroutine.

https://blog.golang.org/defer-panic-and-recover

文档/规范也包含以下内容:

The docs / spec also includes the same :

在执行函数F时,显式调用panic或运行时 恐慌会终止F的执行.F推迟的任何功能都是 然后照常执行.接下来,由F的调用者运行的所有延迟函数 运行,依此类推,直到被顶层功能延迟 执行goroutine .此时,程序终止,并且 报告错误情况,包括要传递的参数值 恐慌.此终止序列称为恐慌

While executing a function F, an explicit call to panic or a run-time panic terminates the execution of F. Any functions deferred by F are then executed as usual. Next, any deferred functions run by F's caller are run, and so on up to any deferred by the top-level function in the executing goroutine. At that point, the program is terminated and the error condition is reported, including the value of the argument to panic. This termination sequence is called panicking

https://golang.org/ref/spec#Handling_panics

这篇关于在go例程中处理恐慌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆