mirror of
https://gitee.com/shikong-sk/golang-study
synced 2025-02-22 23:12:15 +08:00
docs: Panic Recover 异常处理
This commit is contained in:
parent
8a5fe71102
commit
9a0408f6cc
38
base/panic/main.go
Normal file
38
base/panic/main.go
Normal file
@ -0,0 +1,38 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func f1() {
|
||||
fmt.Println("A")
|
||||
}
|
||||
|
||||
func f2() {
|
||||
// defer 在 panic 抛出之前执行
|
||||
// defer 必须 在 可能引发 panic 的语句之前定义
|
||||
defer func() {
|
||||
fmt.Println("defer: 执行")
|
||||
|
||||
// 使用 recover 恢复执行
|
||||
// 返回值为 nil 则无异常
|
||||
err := recover()
|
||||
if err != nil {
|
||||
fmt.Println("recover:", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// 抛出异常 程序退出
|
||||
panic("抛出异常")
|
||||
fmt.Println("B")
|
||||
}
|
||||
|
||||
func f3() {
|
||||
fmt.Println("C")
|
||||
}
|
||||
|
||||
func main() {
|
||||
f1()
|
||||
f2()
|
||||
f3()
|
||||
}
|
Loading…
Reference in New Issue
Block a user