正常的函數(shù)執(zhí)行流程將立即終止,但函數(shù)中之前使用defer關(guān)鍵字延遲執(zhí)行的語句將正常展開執(zhí)行,之后該函數(shù)將返回到調(diào)用函數(shù),并導(dǎo)致逐層向上執(zhí)行panic()流程,直到所屬的goroutine中所有正在執(zhí)行的函數(shù)將被終止。錯誤信息將被報告,包括panic()的參數(shù)類型interface()我們可以看到,panic可以接收任意類型的數(shù)據(jù)
panic(404)
panic("network borken")
panic("Error("file not exists")
發(fā)展壯大離不開廣大客戶長期以來的信賴與支持,我們將始終秉承“誠信為本、服務(wù)至上”的服務(wù)理念,堅持“二合一”的優(yōu)良服務(wù)模式,真誠服務(wù)每家企業(yè),認真做好每個細節(jié),不斷完善自我,成就企業(yè),實現(xiàn)共贏。行業(yè)涉及水電改造等,在網(wǎng)站建設(shè)公司、全網(wǎng)營銷推廣、WAP手機網(wǎng)站、VI設(shè)計、軟件開發(fā)等項目上具有豐富的設(shè)計經(jīng)驗。
recover函數(shù)用于終止錯誤處理流程。recover應(yīng)該在defer關(guān)鍵字的函數(shù)中執(zhí)行以有效截取錯誤處理流程
package main
import (
"fmt"
)
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("detail:", r)
}
}()
fmt.Println("before painc")
panic("error1")
panic("error2")
fmt.Println("after panic")
return
}
運行結(jié)果
before painc
detail: error1
package main
import (
"fmt"
)
func main() {
fmt.Println("before painc")
panic("error1")
panic("error2")
fmt.Println("after panic")
return
}
運行結(jié)果
before painc
panic: error1
goroutine 1 [running]:
main.main()
/home/kenmy/go/src/github.com/shadowsocks/shadowsocks-go/sample-config/panic.go:17 +0xdd
package main
import (
"fmt"
)
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("detail:", r)
}
}()
test()
fmt.Println("end")
return
}
func test() {
defer func() {
if r := recover(); r != nil {
fmt.Println("detail0:", r)
}
}()
fmt.Println("before painc")
panic("error1")
panic("error2")
fmt.Println("after panic")
}
運行結(jié)果
before painc
detail0: error1
end
package main
import (
"fmt"
)
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("detail:", r)
}
}()
test()
fmt.Println("middle")
panic("error3")
fmt.Println("end")
return
}
func test() {
defer func() {
if r := recover(); r != nil {
fmt.Println("detail0:", r)
}
}()
fmt.Println("before painc")
panic("error1")
panic("error2")
fmt.Println("after panic")
}
運行結(jié)果
before painc
detail0: error1
middle
detail: error3
package main
import (
"fmt"
)
func main() {
test()
fmt.Println("middle")
panic("error3")
fmt.Println("end")
return
}
func test() {
fmt.Println("before painc")
panic("error1")
panic("error2")
fmt.Println("after panic")
}
運行結(jié)果:
before painc
panic: error1
goroutine 1 [running]:
main.test()
/home/kenmy/go/src/github.com/shadowsocks/shadowsocks-go/sample-config/panic.go:20 +0xdd
main.main()
/home/kenmy/go/src/github.com/shadowsocks/shadowsocks-go/sample-config/panic.go:10 +0x26