Go Error Handling
Go Language - Error Handling
Go provide a simple framework for error handling along with the built-inerrorinterface which is similar to fmt.Stringer. It uses the error values to show an abnormal state. The fmtpackage will check for the errorinterface while printing values. The error state for Go programs will be expressed with the errorvalues.
Syntax
type error interface {
Error() string
}
Errors should be handled by calling code by testing if the error equals nil. If a non-nil error occurs means failure else if a nil error occurs means success.
Program Example :
CODE/PROGRAM/EXAMPLE
i, err := strconv.Atoi("35") // nil error example
if err != nil {
fmt.Printf("not able to convert the number: %v\n", err)
return
}
fmt.Println("Converted integer:", i)
Error Type :
The error type is predeclared in universe block with all the other built in types. The unexported errorString type from errors package is the most commonly used error implementation.
CODE/PROGRAM/EXAMPLE
// errorString is a commonly-used implementation of error.
type errorString struct {
str string
}
func (e *errorString) Error() string {
return e.str
}
The fmt.Errorf formats a string based on printf rule and returns the error declared by errors.New(). Since the error is an interface, to look into the details of the error, the arbitrary data structures can be used as the error values. Functions often returns the last return value as the error. For constructing a basic error message, use errors.New().
The error interface requires Error method and specific methods are available in the specific error implementations. For instance, the net.Error interface returns the type error and have additional methods.
CODE/PROGRAM/EXAMPLE
package net /*net.Error package*/
type Error interface {
error
Timeout() bool // Is the error a timeout?
Temporary() bool // Is the error temporary?
}
if nerr, ok := err.(net.Error); ok && nerr.Temporary() {
time.Sleep(1e9)
continue
}
if err != nil {
log.Fatal(err)
}
Program Example : /* errors.New Example*/
CODE/PROGRAM/EXAMPLE
package main
import "errors"
import "fmt"
import "math"
func Sqrt(value float64)(float64, error) {
if(value < 0){
return 0, errors.New("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)
}
}
Sample output:
Negative number passed to Sqrt