mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-11-13 17:36:12 +08:00
update book code
This commit is contained in:
44
eBook/exercises/chapter_13/panic_defer.go
Executable file
44
eBook/exercises/chapter_13/panic_defer.go
Executable file
@@ -0,0 +1,44 @@
|
||||
// panic_defer.go
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
f()
|
||||
fmt.Println("Returned normally from f.")
|
||||
}
|
||||
|
||||
func f() {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
fmt.Println("Recovered in f", r)
|
||||
}
|
||||
}()
|
||||
fmt.Println("Calling g.")
|
||||
g(0)
|
||||
fmt.Println("Returned normally from g.")
|
||||
}
|
||||
|
||||
func g(i int) {
|
||||
if i > 3 {
|
||||
fmt.Println("Panicking!")
|
||||
panic(fmt.Sprintf("%v", i))
|
||||
}
|
||||
defer fmt.Println("Defer in g", i)
|
||||
fmt.Println("Printing in g", i)
|
||||
g(i + 1)
|
||||
}
|
||||
/* Output:
|
||||
Calling g.
|
||||
Printing in g 0
|
||||
Printing in g 1
|
||||
Printing in g 2
|
||||
Printing in g 3
|
||||
Panicking!
|
||||
Defer in g 3
|
||||
Defer in g 2
|
||||
Defer in g 1
|
||||
Defer in g 0
|
||||
Recovered in f 4
|
||||
Returned normally from f.
|
||||
*/
|
||||
Reference in New Issue
Block a user