Error handling 在没有恢复的情况下检查恐慌

Error handling 在没有恢复的情况下检查恐慌,error-handling,go,Error Handling,Go,在defer函数中,我想看看对recover的调用是否会产生非nil值(不进行恢复) 有可能吗?那完全是不可能的。您可能只是想重新恐慌,基本上就像在其他语言中重新抛出异常一样 defer func() { if e := recover(); e != nil { //log and so other stuff panic(e) } }()

在defer函数中,我想看看对recover的调用是否会产生非nil值(不进行恢复)


有可能吗?

那完全是不可能的。您可能只是想重新恐慌,基本上就像在其他语言中重新抛出异常一样

        defer func() {
             if e := recover(); e != nil {
                 //log and so other stuff
                 panic(e)
             }
          }()

您可以设置bool标志,然后在函数体的末尾将其重置。如果该标志仍然设置在defer中,则您知道最后一条语句没有执行。唯一可能的原因是函数正在恐慌


解决方案没有“直接”路径


只要对任何非零返回
recover
给出的结果重新恐慌就行了。Dave的答案是最有效的。你的问题的答案是一个简单的“不”。你为什么认为你需要这样做?你能扩展你的答案来解释这是如何回答问题的吗?这段代码在做什么?它是如何相关的?这段代码是一个在不恢复的情况下检测死机的示例。堆栈跟踪不会被新的死机覆盖吗?编辑:没关系,它不是
func do() {
    panicking := true
    defer func() {
        if panicking {
            fmt.Println("recover would return !nil here")
        }
    }()

    doStuff()

    panicking = false
}
package main

import(
    "fmt"
    "runtime"
    "regexp"
)


var re_runtimepanicdetector *regexp.Regexp = regexp.MustCompile("runtime/panic.go$");

func tester_for_panic( deferdepth int )bool{
    _,file,_,_ := runtime.Caller(deferdepth+3)
    return re_runtimepanicdetector.MatchString(file)
}

func tester_for_panic_worktest() bool {
    defer func(){ 
        recover() ;
        if !tester_for_panic(0) { panic("tester_for_panic: NOT WORK!!") } 
    }();
    panic(1)
}
var Iswork_tester_for_panic bool= tester_for_panic_worktest();


func testp( dopanic bool ) {  
        defer func() { 
            fmt.Println("defer panic=", tester_for_panic(0)) ; 
            recover() // optional   
        }()
     if (dopanic) { panic("test")  }
    }


func main(){
    testp(true) 
    testp(false)
}