普通网友 2018-09-19 03:53
浏览 132
已采纳

即使例程在Golang中发生了“运行时错误”,如何“保持主线程运行”?

I am new to Goland and I did Java in the past. I've written a Golang function to calculate the integer number part of the result. What I am thinking is using a timer to do the calculation and generate the random number. But one problem I met is if the routine has some error, the main thread will stop. Is there any way to keep the main thread running? Even though there are errors in routine?

Below is the code for test:

func main() {
    ticker := time.NewTicker(1*1000 * time.Millisecond)
    for _ = range ticker.C {
        rand.Seed(time.Now().Unix())
        divisor := rand.Intn(20)
        go calculate(divisor)
    }
}

func calculate(divisor int){
    result:= 100/divisor
    fmt.Print("1/"+strconv.Itoa(divisor)+"=")
    fmt.Println(result)
}

As the error handling for Golang really confused me, as what I am thinking is the error occurs in the "thread", the main function is just responsible to create the thread and assign task, it should never mind whether there are exceptions occurs in the "threads" and main should always keep going. If I do this in Java, I could use try catch to surround with

try{
    result = 1/divisor;
}
catch(Exception e){
    e.printTrace();
}

even every time I give divisor a 0 value in a separate thread, the main progress will not exit, but for Golang, I think

go calculate(divisor)

is opening a new "thread" and run calculate inside the "thread", but why the main progress will quit. Is there any possible method to prevent the main progress to quit?

Thanks.

  • 写回答

1条回答 默认 最新

  • duanpuqi9965 2018-09-19 10:07
    关注

    use the defer/ recover feature

    package main
    
    import (
        "fmt"
        "time"
        "math/rand"
    )
    
    func main() {
    
        ticker := time.NewTicker(1*1000 * time.Millisecond)
        for _ = range ticker.C {
            rand.Seed(time.Now().Unix())
            divisor := rand.Intn(20)
            go calculate(divisor)
        }
    fmt.Println("that's all")
    }
    
    
    
    func calculate(divisor int){
    defer func() {
            if r := recover(); r != nil {
                fmt.Println("Recovered in f", r)
            }
        }()
        result:= 100/divisor
        fmt.Printf("1/%d=", divisor)
        fmt.Println(result)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 vscode的问题提问
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM