错误处理机制-defer + recover 来捕获错误

This commit is contained in:
2025-11-09 13:47:53 +08:00
parent 98600cd598
commit 888b110ba2

28
main.go
View File

@@ -3,24 +3,18 @@ package main
import "fmt"
func main() {
//定义一个函数类型的变量
a := test
fmt.Printf("a 的变量类型是 %T\n", a)
a(1)
b(2, 3, a)
// 自定义数据类型,别名
type myInt int
var sb1 myInt = 42
fmt.Println(sb1)
test()
fmt.Println("程序执行成功")
}
func test(a int) {
fmt.Println(a)
func test() {
defer func() {
err := recover()
if err != nil {
fmt.Println("test发生错误", err)
}
// 可传入函数类型变量
func b(a int, b int, c func(int)) {
c(a + b)
}()
a := 1
b := 0
fmt.Println(a / b)
}