MyTetra Share
Делитесь знаниями!
Error Handling
Время создания: 01.10.2017 15:10
Раздел: Go
Запись: xintrea/mytetra_db_mcold/master/base/1506859825q464gh30uv/text.html на raw.githubusercontent.com

Go programming provides a pretty simple error handling framework with inbuilt error interface type of the following declaration −

type error interface {
   Error() string
}

Functions normally return error as last return value. Use errors.New to construct a basic error message as following −

func Sqrt(value float64)(float64, error) {
   if(value < 0){
      return 0, errors.New("Math: negative number passed to Sqrt")
   }
   return math.Sqrt(value)
}

Use return value and error message.

result, err:= Sqrt(-1)

if err != nil {
   fmt.Println(err)
}

Example

package main

import "errors"
import "fmt"
import "math"

func Sqrt(value float64)(float64, error) {
   if(value < 0){
      return 0, errors.New("Math: negative number passed to Sqrt")
   }
   return math.Sqrt(value), nil
}
func main() {
   result, err:= Sqrt(-1)

   if err != nil {
      fmt.Println(err)
   } else {
      fmt.Println(result)
   }
   
   result, err = Sqrt(9)

   if err != nil {
      fmt.Println(err)
   } else {
      fmt.Println(result)
   }
}

When the above code is compiled and executed, it produces the following result −

Math: negative number passed to Sqrt
3
 
MyTetra Share v.0.65
Яндекс индекс цитирования