go 错误处理

package main
import "fmt"
func main(){
	//正常情况
	if result,errorMsg := Divide(100,10);errorMsg == "" {
		fmt.Println("100 / 10 = ",result)
	}

	//不正常情况
	if _,errorMsg := Divide(90,0); errorMsg != "" {
		fmt.Println("errorMsg is ",errorMsg)
	}
}
//定义一个DivideError结构
type DivideError struct{
	dividee int
	divider int
}

//实现error接口
func (de *DivideError) Error() string{
	strFormat := `
	Cannot proceed,the divider is zero.
	dividee:%d
	divider:0
`
	return fmt.Sprintf(strFormat,de.dividee)
}

//定义 int 类型除法运算的函数
func Divide(varDividee int, varDivider int) (result int,errorMsg string){
	if varDivider == 0 {
		dData := DivideError{
			dividee:varDividee,
			divider:varDivider,
		}
		errorMsg = dData.Error()
		return
	}else{
		return varDividee / varDivider, ""
	}
}

你可能感兴趣的:(go语言,golang,算法,开发语言)