Go 实现异常处理机制

实例:

 1 package main
 2 
 3 import "fmt"
 4 
 5 type DevideError struct {
 6     devidee int
 7     devider int
 8 }
 9 
10 func (de *DevideError) Error() string {
11     strFormat := `
12     Cannot proceed, the divider is zero.
13     dividee: %d
14     divider: 0
15 `
16     return fmt.Sprintf(strFormat, de.devidee)
17 }
18 
19 func Devide(varDevidee int, varDevider int) (result int, errorMsg string)  {
20     if varDevider == 0 {
21         dData := DevideError {
22             devidee: varDevidee,
23             devider: varDevider,
24         }
25         errorMsg = dData.Error()
26         return
27     } else {
28         return varDevidee / varDevider, ""
29     }
30 }
31 
32 func main()  {
33     if result, errorMsg := Devide(100, 10); errorMsg == "" {
34         fmt.Println("100/10 = ", result)
35     }
36 
37     if _, errorMsg := Devide(100, 0); errorMsg != "" {
38         fmt.Println("errorMsg is :", errorMsg)
39     }
40 }

运行结果:

100/10 =  10
errorMsg is : 
    Cannot proceed, the divider is zero.
    dividee: 100
    divider: 0

 

posted @ 2019-01-23 16:39  UniqueColor  阅读(305)  评论(0编辑  收藏  举报