錯誤和異常的區(qū)別是,錯誤是業(yè)務邏輯的一部分,異常不是。而且異常有可能終止業(yè)務邏輯。在golang中,異常不要用來代替錯誤,更不要用來控制流程。
golang提供了panic, recover和defer來實現(xiàn)異常的拋出和捕捉。
函數(shù)中調(diào)用panic()拋出異常后,程序會馬上中止當前的運行,跳轉到延時調(diào)用(defer語句),如果defer中調(diào)用了recover(),則異常被捕捉,程序繼續(xù)執(zhí)行;否則,當前函數(shù)的defer執(zhí)行完后返回到上一個調(diào)用函數(shù)執(zhí)行defer,如果到最頂層函數(shù)都沒遇到recover(),程序崩潰打印出調(diào)試信息并終止。
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() {// // 函數(shù)體
// 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
你是否還在尋找穩(wěn)定的海外服務器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機房具備T級流量清洗系統(tǒng)配攻擊溯源,準確流量調(diào)度確保服務器高可用性,企業(yè)級服務器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧
分享標題:golangexceptionerror異常錯誤處理-創(chuàng)新互聯(lián)
文章地址:http://chinadenli.net/article2/dephic.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供云服務器、網(wǎng)站設計、手機網(wǎng)站建設、小程序開發(fā)、服務器托管、營銷型網(wǎng)站建設
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容