funcmain() { f() fmt.Println("Returned normally from f.") }
funcf() { // 被推延至結束才執行,並且recover() 會接受panic所傳遞的參數 deferfunc() { if r := recover(); r != nil { fmt.Println("Recovered in f", r) } }() fmt.Println("Calling g.") g(0) fmt.Println("Returned normally from g.") }
funcg(i int) { if i > 3 { fmt.Println("Panicking!") panic(fmt.Sprintf("%v", i)) } // 將 印出“Defer in g"這段訊息 延後印出,直到panic觸發或是程式結束才會被印出來 // 先被defer的會最晚被印出來,為Last in first out ! defer fmt.Println("Defer in g", i) fmt.Println("Printing in g", i) g(i + 1) }
1 2 3 4 5 6 7 8 9 10 11 12
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.