golang exception error 异常 错误 处理

golang exception error 异常 错误 处理

错误和异常的区别是,错误是业务逻辑的一部分,异常不是。而且异常有可能终止业务逻辑。在golang中,异常不要用来代替错误,更不要用来控制流程。

golang提供了panic, recover和defer来实现异常的抛出和捕捉。

函数中调用panic()抛出异常后,程序会马上中止当前的运行,跳转到延时调用(defer语句),如果defer中调用了recover(),则异常被捕捉,程序继续执行;否则,当前函数的defer执行完后返回到上一个调用函数执行defer,如果到最顶层函数都没遇到recover(),程序崩溃打印出调试信息并终止。

package main

import (
	"fmt"
	//"github.com/handsomestWei/go-exception/exception"

	"github.com/manucorporat/try"
	//"github.com/qianlnk/exception"
)
func fun() {
    
    
	defer fmt.Println("defer 1")
	defer fmt.Println("defer 2")
	fmt.Println("fun")
}
func main() {
    
    
	//fun()

	//faa()
	//fmt.Println("Returned normally from f.")

	try.This(func() {
    
    
		panic("my panic")

	}).Finally(func() {
    
    
		fmt.Println("this must be printed after the catch")

	}).Catch(func(e try.E) {
    
    
		// Print crash
		fmt.Println("aaaaa")
		fmt.Println(e)
		fmt.Println("bbbbb")
	})

	//tr := exception.New()
	//tr.Try(
	//	func() {
    
    
	//		n1, err := strconv.Atoi("123a")
	//		tr.Throw(err)
	//		n2, err := strconv.Atoi("0")
	//		tr.Throw(err)
	//		res := n1 / n2
	//		fmt.Println(res)
	//	},
	//).Catch(
	//	func(e exception.Exception) {
    
    
	//		fmt.Println("exception:", e)
	//	},
	//)

	//tr := exception.NewTrier()
	//tr.Try(func() {
    
    
	//	// 函数体
	//	n1, err := strconv.Atoi("123")
	//	tr.Throw(err)
	//	n2, err := strconv.Atoi("qwe")
	//	tr.Throw(err)
	//	res := n1 / n2
	//	fmt.Println(res)
	//}).Catch(func(e exception.Exception) {
    
    
	//	// 捕获异常和异常处理
	//	fmt.Println("exception:", e)
	//}).Finally(func() {
    
    
	//	// 事后处理
	//	fmt.Println("finally")
	//})
}

func faa() {
    
    
	fmt.Println("Calling g(0).")
	g(0)
	fmt.Println("Returned normally from g(0).")
}
func g(i int) {
    
    
	defer func() {
    
    
		if r := recover(); r != nil {
    
    
			fmt.Println("Recovered in g", r)
		}
	}()
	defer fmt.Println("Defer in g", i)
	fmt.Println("Panic!")
	panic("panic in g")
	fmt.Println("Printing in g", i)
}

参考链接:
http://blog.chinaunix.net/uid-24716553-id-5692869.html
https://github.com/manucorporat/try
https://github.com/handsomestWei/go-exception
https://github.com/qianlnk/exception
https://golangtc.com/t/592aee76b09ecc1870000090

猜你喜欢

转载自blog.csdn.net/yinjl123456/article/details/128191253