0
0
Goprogramming~5 mins

Handling errors in Go

Choose your learning style9 modes available
Introduction

Errors happen when something goes wrong in a program. Handling errors helps your program respond nicely instead of crashing.

When reading a file that might not exist
When connecting to the internet and the connection fails
When converting user input to a number and the input is wrong
When calling a function that might return an error
When working with databases and queries might fail
Syntax
Go
value, err := someFunction()
if err != nil {
    // handle the error
    return
}
// continue using value

In Go, errors are values returned by functions.

You check if the error is not nil to see if something went wrong.

Examples
This example tries to open a file and prints an error if it fails.
Go
file, err := os.Open("file.txt")
if err != nil {
    fmt.Println("Error opening file:", err)
    return
}
// use file
This example converts a string to a number and handles the error if the string is not a valid number.
Go
num, err := strconv.Atoi("123a")
if err != nil {
    fmt.Println("Conversion error:", err)
} else {
    fmt.Println("Number is", num)
}
Sample Program

This program tries to convert a string to a number. If it fails, it prints an error message and stops. Otherwise, it prints the number.

Go
package main

import (
    "fmt"
    "strconv"
)

func main() {
    input := "42a"
    number, err := strconv.Atoi(input)
    if err != nil {
        fmt.Println("Oops! Could not convert input to number:", err)
        return
    }
    fmt.Println("The number is", number)
}
OutputSuccess
Important Notes

Always check errors right after calling a function that returns one.

Handling errors early helps avoid bigger problems later.

You can create your own error messages using errors.New or fmt.Errorf.

Summary

Errors in Go are values returned by functions.

Check if error is not nil to see if something went wrong.

Handle errors to keep your program safe and user-friendly.