Menu
Coddy logo textTech

Basic Error Handling

Part of the Fundamentals section of Coddy's GO journey — lesson 108 of 109.

Basic Error Handling is a fundamental pattern in Go where you check for errors after operations that might fail.

Let's learn how to handle errors in Go by creating a simple division function that returns an error when dividing by zero:

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

This function returns two values: the result of division and an error. If the divisor is zero, it returns an error message instead of attempting the division.

Now, let's see how to use this function and handle any potential errors:

result, err := divide(10, 0)
    
if err != nil {
    fmt.Println("Error occurred:", err)
    return // Stop execution or handle the error
}
    
fmt.Println("Result:", result)

After executing this code, we check if an error occurred using the if err != nil condition. Since we tried to divide by zero, the function returns an error, and the following will show on the screen:

Error occurred: division by zero

This pattern of returning an error as the last return value and immediately checking it is very common in Go. It allows your program to gracefully handle failures instead of crashing.

challenge icon

Challenge

Easy

In this challenge, you'll practice basic error handling in Go. You have a function that divides two numbers, but division by zero causes a runtime error. Your task is to add error handling to prevent this crash.

The code already has a function that returns both a result and an error. You need to check if there's an error before using the result.

Cheat sheet

In Go, functions that might fail return an error as the last return value:

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

Check for errors using if err != nil:

result, err := divide(10, 0)
    
if err != nil {
    fmt.Println("Error occurred:", err)
    return // Stop execution or handle the error
}
    
fmt.Println("Result:", result)

This pattern allows programs to handle failures gracefully instead of crashing.

Try it yourself

package main

import (
	"errors"
	"fmt"
)

// This function divides x by y and returns an error if y is zero
func divide(x, y float64) (float64, error) {
	if y == 0 {
		return 0, errors.New("cannot divide by zero")
	}
	return x / y, nil
}

func main() {
	// Test values
	numerator := 10.0
	denominator := 0.0
	
	// Call the divide function
	result, err := divide(numerator, denominator)
	
	// TODO: Check if err is not nil (there is an error)
	// If there is an error, print it using fmt.Println(err)
	// Otherwise, print the result using fmt.Printf("Result: %.2f\n", result)
	
	// Remove this line and implement proper error handling above
	fmt.Printf("Result: %.2f\n", result)
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals