doubengshao8872 2015-02-11 09:59
浏览 33
已采纳

如何应对外界的恐慌

Look at the following code snippet.

package main

import "fmt"

func explode() {
    // Cause a panic.
    panic("WRONG")
}

func recovery() int {
    explode()
    defer func() {
        fmt.Println("Try to handle panic")
        if err := recover(); err != nil {
            fmt.Println("FIX")
            fmt.Println("ERR", err)
        }
    }()
    fmt.Println("Print value")
    return 100

}

func main() {
    // Handle errors in defer func with recover.
    fmt.Println(recovery())
}

As you can see code above, I fired a panic in the explode function and want to handle it in the recovery function. But the panic does not get caught, I've got runtime error

goroutine 1 [running]:
main.explode()
        D:/gocode/src/samples/panic1.go:7 +0x6b
main.recovery(0xc082002250)
        D:/gocode/src/samples/panic1.go:18 +0x26
main.main()
        D:/gocode/src/samples/panic1.go:27 +0x26

goroutine 2 [runnable]:
runtime.forcegchelper()
        c:/go/src/runtime/proc.go:90
runtime.goexit()
        c:/go/src/runtime/asm_amd64.s:2232 +0x1

goroutine 3 [runnable]:
runtime.bgsweep()
        c:/go/src/runtime/mgc0.go:82
runtime.goexit()
        c:/go/src/runtime/asm_amd64.s:2232 +0x1

goroutine 4 [runnable]:
runtime.runfinq()
        c:/go/src/runtime/malloc.go:712
runtime.goexit()
        c:/go/src/runtime/asm_amd64.s:2232 +0x1
exit status 2

How to catch the panic in the recory function?

  • 写回答

1条回答 默认 最新

  • douningqiu4991 2015-02-11 10:02
    关注

    If you call explode() first, the function that would handle the panic and try to recover is not yet registered (and never will be because you call panic inside explode()), so it won't be called and obviously it can't do its work.

    You have to call defer first and then the explode() function:

    defer func() {
        // recover() here, Your code omitted
    }()
    explode()
    

    Try it on the Go Playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来