前言
習慣了java的try catch方式,由於go語言中沒有try catch機制,所以自己封裝了一個。
代碼
catch_panic.go
package Try
/**
* 捕獲異常try...catch
* 用法示例:
* defer Try.CatchException(func(e interface{}){
* log.Printf("%s\n", e)
* })
*/
func CatchException(handle func(e interface{})) {
if err := recover(); err != nil {
handle(err)
}
}
main.go
package main
import (
"./Try"
"log"
)
func main() {
defer Try.CatchException(func(e interface{}){
log.Printf("%s\n", e)
})
panic("This is a panic test.")
}