English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang Basic Tutorial

Golang Control Statements

Golang Function & Method

Golang Struct

Golang Slice & Array

Golang String(String)

Golang Pointer

Golang Interface

Golang Concurrency

Golang Exception(Error)

Golang Other Miscellaneous

Go Language Error (Error Handling)

Go does not have a try like Java / catch such exception mechanisms, we cannot throw exceptions in Go.

Go uses another mechanism calledDeferral panic and recovery mechanism.

Go handles simple errors in functions and methods by returning an error object. The error object may be the only or last return value. If there is no error in the function, the error object is nil.

Whether or not an error is received, we should always check for errors in the call statement.

We should never ignore errors as they can cause the program to crash.

The way Go language detects and reports error conditions is

  • Functions that may cause errors will return two variables: a value and an error code, which is nil if successful; if an error condition occurs, it is != nil.

  • Check for errors after function calls. If an error occurs (if error != nil), stop executing the actual function (or the entire program if necessary).

Go has a predefined error interface type

type error interface {
    Error() string
}	

We can use the error.New function in the error package to define an error type and provide an appropriate error message, for example:

err := errors.New("math" - Negative number's square root")

Error 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's square root")
   }
   return math.Sqrt(value), nil
}
func main() {
   result, err := Sqrt(-64)
   if err != nil {
      fmt.Println(err)
   } else {
      fmt.Println(result)
   }
   result, err = Sqrt(64)
   if err != nil {
      fmt.Println(err)
   } else {
      fmt.Println(result)
   }
}

Output:

Math: Square Root of Negative Numbers
8