Last active
March 3, 2019 04:34
-
-
Save bwangelme/9ce1c606ba9f69c72f82722adf1402e1 to your computer and use it in GitHub Desktop.
以下代码展示了如何将 panic 转换成 error 并返回
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
//calNumber | |
//以下代码展示了如何将 panic 转换成 error 并返回 | |
func calNumber() (res int, err error) { | |
defer func() { | |
if p := recover(); p != nil { | |
err = fmt.Errorf("%s", p) | |
} | |
}() | |
div := 0 | |
res = 10 / div | |
return | |
} | |
func main() { | |
_, err := calNumber() | |
if err != nil { | |
fmt.Printf("Get error: `%s`\n", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment