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

error:
http://www.jb51.net/article/106207.htm

package main

import "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

你可能感兴趣的:(golang异常处理panic和defer的使用)