golang异常处理panic和defer的使用
简洁的panic recover代码:
https://www.cnblogs.com/songxingzhu/p/5255485.html
https://www.cnblogs.com/baiyuxiong/p/4770980.html
panic recover error 几个概念的说明:
https://blog.csdn.net/wuwenxiang91322/article/details/9042503
异常处理的几个例子:
https://www.jianshu.com/p/f30da01eea97
【golang异常处理panic和defer的使用】error:
http://www.jb51.net/article/106207.htm
package mainimport "fmt"func main() {
// defer func() {
//if err := recover();
err != nil {
//fmt.Println("出了错:", err)
//}
// }()
a := []int{6, 1, 10, 2, 7, 3, 8, 9, 2, 4}
sort(a, 0, len(a))
fmt.Println("a:", a)
myPainc()
sefPainc()
}func sort(a []int, left, right int) {
defer func() {
if err := recover();
err != nil {
fmt.Println("出了错:", err)
}
}()
if left >= right {
return
}
i, j := left, right
key := a[left]
for i < j {
for i < j && key <= a[j] {
j--
}
a[i] = a[j]
for i < j && key >= a[i] {
i++
}
a[j] = a[i]
}
a[i] = key
sort(a, left, i-1)
sort(a, i+1, right)
}func myPainc() {
defer func() {
if err := recover();
err != nil {
fmt.Println("出了错:", err)
}
}()
var x = 30
var y = 0
//panic("我就是一个大错误!")
var c = x / y
fmt.Println("c is:", c)
}func sefPainc() {
defer func() {
if err := recover();
err != nil {
fmt.Println("出了错:", err)
}
}()
panic("sefpainc")
}
结果
出了错: runtime error: index out of range
a: [6 1 10 2 7 3 8 9 2 4]
出了错: runtime error: integer divide by zero
出了错: sefpainc
推荐阅读
- Java|Java OpenCV图像处理之SIFT角点检测详解
- 事件处理程序
- 爬虫数据处理HTML转义字符
- python-安装sublime遇到异常
- Android|Android BLE蓝牙连接异常处理
- 三门问题(蒙提霍尔悖论)分析与Golang模拟
- 【冷处理】亲子时间管理检视Day63
- C#中类的异常处理详解
- JAVA图像处理系列(四)——噪声
- Promise详解