golangexceptionerror异常错误处理-创新互联

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

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


本文题目:golangexceptionerror异常错误处理-创新互联
网页地址:http://ybzwz.com/article/dephic.html