0
0
Goprogramming~5 mins

Error interface in Go

Choose your learning style9 modes available
Introduction

The Error interface in Go helps programs tell when something went wrong. It gives a simple way to share error messages.

When a function might fail and you want to tell the caller what happened.
When you want to check if a problem occurred before continuing.
When you want to return a clear message about an issue in your code.
When you want to handle different errors differently in your program.
Syntax
Go
type error interface {
    Error() string
}

The Error interface has one method: Error() which returns a string message.

Any type that has this method is an error and can be used as one.

Examples
Create a new error with a message using the errors.New function.
Go
var err error = errors.New("file not found")
Return an error if dividing by zero, otherwise return the result and no error (nil).
Go
func divide(a, b int) (int, error) {
    if b == 0 {
        return 0, fmt.Errorf("cannot divide by zero")
    }
    return a / b, nil
}
Sample Program

This program checks if a person is old enough. If not, it returns an error with a message. The main function prints the error message.

Go
package main

import (
    "errors"
    "fmt"
)

func checkAge(age int) error {
    if age < 18 {
        return errors.New("age must be at least 18")
    }
    return nil
}

func main() {
    age := 16
    if err := checkAge(age); err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Age is fine")
    }
}
OutputSuccess
Important Notes

Always check if the error is nil before using the result from a function.

You can create your own error types by making a struct that implements the Error() method.

Summary

The Error interface has one method Error() that returns a message.

Functions return errors to show problems.

Check errors before using results to avoid bugs.