golang 異常處理
- panic: 用來創造異常
- recover 用來獲取異常,不能直接獲取,需要與defer一起使用。
- defer : 在函數結束時調用,處理異常與資源回收等操作。
代碼:
package main
import (
"fmt"
"os"
)
func main() {
foo()
fmt.Println("main run other function...")
}
func foo() {
defer func() {
if err := recover(); err != nil {
fmt.Println("catch exception...", err)
}
fmt.Println("other operation...")
}()
_, err := os.Open("E:/not_exists_file")
if err != nil {
panic(err)
}
}