普通网友 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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集