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

报告相同问题?