内容简介:一、知识点、1、用到go 关键字定位2、用到defer 延后处理最终执行
一、知识点、
1、用到 go 关键字定位
2、用到defer 延后处理最终执行
3、panic,相当于try
4、recover ,相当于catch
5、内置函数说明:
image.png
二、代码
、、、
package main
import (
"fmt"
"time"
)
func serve(ch <-chan int) {
for val := range ch {
go handle(val)
}
}
func handle(x int) {
defer func() {
if err := recover(); err != nil {
fmt.Println("work failed at :", err)
}
}()
if x == 4 {
panic(x)
}
fmt.Println("work successed at :", x)
}
func main() {
var ch = make(chan int, 6)
for i := 1; i <= 6; i++ {
ch <- i
}
close(ch)
go serve(ch)
time.Sleep(time.Millisecond * 100)
}
、、、
三、图片及运行结果
image.png
以上所述就是小编给大家介绍的《panic+recover golang 中的try catch》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Nature of Code
Daniel Shiffman / The Nature of Code / 2012-12-13 / GBP 19.95
How can we capture the unpredictable evolutionary and emergent properties of nature in software? How can understanding the mathematical principles behind our physical world help us to create digital w......一起来看看 《The Nature of Code》 这本书的介绍吧!