V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
yezheyu
V2EX  ›  问与答

go 语言新手,请教个关于异常的问题

  •  
  •   yezheyu · 6 天前 · 309 次点击

    为啥下面这段代码,未捕获到 panic

    package main
    
    import "fmt"
    
    func main() {
        defer func() {
        	fmt.Println("-----") // 未执行
            if err := recover(); err != nil {
                fmt.Println("捕获到 panic:", err)
            }
        }()
        1 / 0
    }
    
    // 输出:
    // # command-line-arguments
    // ./a.go:11:9: invalid operation: division by zero
    

    而手动抛出 panic ,则可以被捕获到

    package main
    
    import "fmt"
    
    func main() {
        defer func() {
        	fmt.Println("-----") // 执行
            if err := recover(); err != nil {
                fmt.Println("捕获到 panic:", err)
            }
        }()
        panic("+++++")
    }
    
    // 输出:
    // -----
    // 捕获到 panic: +++++
    
    Rickkkkkkk
        1
    Rickkkkkkk  
       6 天前
    除零不可以被 recover 的,类似的还有并发 map
    Vegetable
        2
    Vegetable  
       6 天前
    不是,你上边的写法都没编译成功,没有真正的运行。
    seth19960929
        3
    seth19960929  
       6 天前
    楼上说的对, 你那个是编译检查错误, 不是运行时错误, 1/0 是可以被捕获成功的, 骗一下编译器

    package main

    import (
    "fmt"
    )

    func main() {
    defer func() {
    if err := recover(); err != nil {
    fmt.Println("捕获到 panic:", err) // 会执行
    }
    }()
    // 通过变量绕过编译器的除零检查
    a, b := 1, 0
    _ = a / b // 运行时 panic: integer divide by zero
    }
    yezheyu
        4
    yezheyu  
    OP
       6 天前
    @Vegetable
    @seth19960929
    懂了,谢谢
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5453 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 21ms · UTC 03:00 · PVG 11:00 · LAX 20:00 · JFK 23:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.