• Go 常见的引发 panic 的情况


    1. 数组下标越界(运行时错误)
    package main
    import "fmt"
    func main() {
        var s []string
        fmt.Println(s)
        fmt.Println(s[0])
    }
    

    运行结果:

    []
    panic: runtime error: index out of range
    
    goroutine 1 [running]:
    main.main()
    
    1. 空指针异常(运行时错误)
    package main
    import "fmt"
    type Person struct {
        Name string
        Age  int
    }
    func main() {
        var p *Person
        fmt.Println(p)
        fmt.Println(p.Name)
    }
    

    运行结果:

    <nil>
    panic: runtime error: invalid memory address or nil pointer dereference
    [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x10914c8]
    
    goroutine 1 [running]:
    main.main()
    
    1. 类型断言失败(接口转换异常)
    package main
    import "fmt"
    func main() {
        add(20, 18)
        add(1, "hello")
    }
    func add(a, b interface{}) {
        i := a.(int)
        j := b.(int)
        fmt.Println(i+j)
    }
    

    运行结果:

    panic: interface conversion: interface {} is string, not int
    38
    
    goroutine 1 [running]:
    main.add(0x10a0f60, 0x10d6840, 0x10a1660, 0x10d6b90)
    
    1. 通道为空,通道已关闭(写数据)
    package main
    func main() {
        var ch chan int
        close(ch)
    }
    

    运行结果:

    panic: close of nil channel
    
    goroutine 1 [running]:
    main.main()
    package main
    func main() {
        var ch chan int
        ch = make(chan int,0)
        close(ch)
        ch <- 108
    }
    

    运行结果:

    panic: send on closed channel
    
    goroutine 1 [running]:
    main.main()
    
    1. 死锁,所有线程睡眠(致命错误)
      这一条是致命错误,不属于异常,但是跟异常一样,会导致程序挂掉。
    package main
    func main() {
        var ch chan int
        ch = make(chan int)
        ch <- 108
    }
    

    运行结果:

    fatal error: all goroutines are asleep - deadlock!
    
    goroutine 1 [chan send]:
    main.main()
    

    http://www.luyixian.cn/news_show_23437.aspx




    链接:https://www.jianshu.com/p/b9a2c59b2dd3

  • 相关阅读:
    POJ 1306.Combinations
    HDU 5640.King's Cake
    HDU 1072.Nightmare
    HDU 2717.Catch That Cow
    HDU 1372.Knight Moves
    HDU 1548.A strange lift
    AOJ 802.运输宝物
    AOJ 794.西瓜理发记(二)
    AOJ 793.西瓜理发记(一)
    AOJ 789.买酒
  • 原文地址:https://www.cnblogs.com/brady-wang/p/15265867.html
Copyright © 2020-2023  润新知