package main import ( "fmt" ) type TryTarget func() type CatchTarget func() func TryAndCatch(target TryTarget,catch CatchTarget) { defer func() { if err := recover(); err != nil { catch() } }() target() } func main() { TryAndCatch(func() { panic("抛出异常") },func() { fmt.Println("异常恢复") }) }
先别说话,亮出代码,关于golang程序的异常处理涉及到三个关键字:
1.panic 把异常抛出去,一旦抛出异常该函数将立刻终止运行,下一步自动跳转到defer语句中
2.defer 语句中执行recover捕获异常,获取异常的具体信息
原文链接:https://www.f2er.com/go/189013.html