0
0
Goprogramming~5 mins

Returning errors in Go

Choose your learning style9 modes available
Introduction

Returning errors helps your program tell when something went wrong. It lets you handle problems safely and clearly.

When a function might fail and you want to tell the caller what happened.
When reading a file that might not exist or be readable.
When dividing numbers and the divisor could be zero.
When connecting to a database that might be down.
When parsing user input that might be invalid.
Syntax
Go
func functionName(params) (returnType, error) {
    if problem {
        return zeroValue, errors.New("error message")
    }
    return result, nil
}

The function returns two values: the result and an error.

If there is no error, return nil for the error.

Examples
This function returns an error if you try to divide by zero.
Go
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("cannot divide by zero")
    }
    return a / b, nil
}
This function returns an error if the name is empty.
Go
func greet(name string) (string, error) {
    if name == "" {
        return "", errors.New("name cannot be empty")
    }
    return "Hello, " + name, nil
}
Sample Program

This program tries to divide two numbers. It prints the result if no error happens. If there is an error, it prints the error message.

Go
package main

import (
    "errors"
    "fmt"
)

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("cannot divide by zero")
    }
    return a / b, nil
}

func main() {
    result, err := divide(10, 2)
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Result:", result)
    }

    result, err = divide(5, 0)
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Result:", result)
    }
}
OutputSuccess
Important Notes

Always check if the error is nil before using the result.

Use errors.New to create simple error messages.

Returning errors helps keep your program safe and clear.

Summary

Functions can return an error to show if something went wrong.

Return nil for error when everything is okay.

Always check errors before using the returned data.