时间:2021-07-01 10:21:17 帮助过:8人阅读
- type division struct {
- arg int
- str string
- }
- func (e *division) Error() string {
- return fmt.Sprintf("%d %s", e.arg, e.str)
- }
- func divideCheck(arg1, arg2 int) (error) {
- if arg2 == 0 {
- return &division{arg1, "can't divided by 0"}
- }
- return nil
- }
- package main
- import "fmt"
- func divideCheck(arg1, arg2 int) (error) {
- if arg2 == 0 {
- return fmt.Errorf("%d can't divided by 0", arg1)
- }
- return nil
- }
- func main() {
- var err error
- err = divideCheck(4, 2)
- if err != nil {
- fmt.Println(err)
- return
- }
- err = divideCheck(8, 0)
- if err != nil {
- fmt.Println(err)
- return
- }
- }
这么做代码就优雅多了,并且在每次检查前都判断内部状态是否已经出错,出错就马上返回,几乎没有性能损失。
- package main
- import "fmt"
- type division struct {
- err error
- }
- func (this *division)DivideCheck(arg1, arg2 int) {
- if this.err != nil {
- return
- }
- if arg2 == 0 {
- this.err = fmt.Errorf("%d can't divided by 0", arg1)
- return
- }
- }
- func (this *division)Err() error {
- return this.err
- }
- func main() {
- d := new(division)
- d.DivideCheck(4, 2)
- d.DivideCheck(8, 0)
- if d.Err() != nil {
- fmt.Println(d.Err())
- }
- }
http://www.bkjia.com/PHPjc/1114325.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1114325.htmlTechArticlegolang错误处理之error golang中没有try/catch这样的异常处理机制,只能依靠返回值来做状态是否出错判断(当然它有个panic/recover机制,但一般只...