Skip to content

Commit 4a0305f

Browse files
committed
20220402
1 parent e38912a commit 4a0305f

File tree

2 files changed

+71
-1
lines changed

2 files changed

+71
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545

4646
[第16章 编写好的错误处理](https://github.com/java-aodeng/golang-examples/blob/master/go-16/err_test.go)
4747

48-
第17章 panic和recover
48+
[第17章 panic和recover](https://github.com/java-aodeng/golang-examples/blob/master/go-17/panic_recover_test.go)
4949

5050
第18章 构建可复用的模块(包)
5151

go-17/panic_recover_test.go

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package go_17
2+
3+
import (
4+
"errors"
5+
"fmt"
6+
"log"
7+
"os"
8+
"testing"
9+
)
10+
11+
//panic
12+
//用于主动抛出错误,类似于java的抛出异常
13+
//panic用于不可以恢复的错误
14+
//panic退出前回执行defer指定的内容
15+
16+
//panic 和os.Exit的区别
17+
//os.Exit退出时不会调用defer指定的函数
18+
//os.Exit退出时不输出当前调用栈信息
19+
20+
//recover
21+
//用于捕获panic抛出的错误,类似于java的异常捕获try{}catch
22+
23+
//使用Exit退出程序
24+
func TestExit(t *testing.T) {
25+
defer func() {
26+
fmt.Print("我是退出前回执的内容")
27+
}()
28+
fmt.Print("Start--》")
29+
os.Exit(-1)
30+
}
31+
32+
//运行结果 :可以看到退出后没有执行defer里面的内容
33+
//=== RUN TestExit
34+
//Start--》
35+
36+
//使用panic抛出异常
37+
func TestPainc(t *testing.T) {
38+
defer func() {
39+
fmt.Print("我是退出前回执的内容")
40+
}()
41+
fmt.Print("Start--》")
42+
panic(errors.New("异常退出"))
43+
}
44+
45+
//运行结果 :可以看到退出后执行defer里面的内容,并且输出当前调用栈信息
46+
//=== RUN TestPainc
47+
//Start--》我是退出前回执的内容--- FAIL: TestPainc (0.00s)
48+
//panic: 异常退出 [recovered]
49+
//panic: 异常退出
50+
//goroutine 19 [running]:
51+
//testing.tRunner.func1(0xc0000a0100)
52+
53+
//使用recover捕获panic抛出的异常
54+
func TestRecover(t *testing.T) {
55+
defer func() {
56+
if err := recover(); err != nil {
57+
//这里可以做"错误恢复"
58+
//常见的的"错误恢复",记录到打印日志里面,但是这样的修复方式是非常危险的,很容易出先僵尸进程,”Let it Crash“往往是我们恢复不确定性错误的最好方法
59+
log.Println("捕获到异常,手动处理异常")
60+
}
61+
}()
62+
fmt.Print("Start")
63+
panic(errors.New("异常退出"))
64+
}
65+
66+
//运行结果 大家可以看到这里输出内容不是"异常退出"也没有打印栈信息了,因为我们手动处理了异常,但是这样做是对程序很危险的一种方式,懒点直接让程序崩溃反而更好,不然服务器炸了,不要让运维有甩锅给开发的机会
67+
//=== RUN TestRecover
68+
//Start2022/04/02 19:21:36 捕获到异常,手动处理异常信息
69+
//--- PASS: TestRecover (0.03s)
70+
//PASS

0 commit comments

Comments
 (0)