Go Error Handling

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Go - Error Handling

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

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

Math: negative number passed to Sqrt
3