Menu
Coddy logo textTech

Checking for Errors

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

In Go, we check for errors using if statements. This pattern is extremely common.

Check if an error occurred using if err != nil:

func main() {
    result, err := divide(10, 0)
    
    if err != nil {
        fmt.Println("Error occurred:", err)
        return // Stop execution if there's an error
    }
    
    // Continue only if no error
    fmt.Println("Result:", result)
}

The output will be:

Error occurred: cannot divide by zero
challenge icon

Challenge

Beginner

In Go, functions often return an error value that you need to check before using the result. In this challenge, you'll practice checking for errors using the if statement.

We have a function called openFile that simulates opening a file and returns an error if the file doesn't exist. Your task is to check if there's an error and print an appropriate message.

Cheat sheet

Check for errors using if err != nil:

result, err := someFunction()

if err != nil {
    fmt.Println("Error occurred:", err)
    return // Stop execution if there's an error
}

// Continue only if no error
fmt.Println("Result:", result)

Try it yourself

package main

import (
	"fmt"
)

// This function simulates opening a file
// It returns an error if the file doesn't exist
func openFile(filename string) error {
	if filename == "data.txt" {
		return nil // nil means no error
	} else {
		return fmt.Errorf("file %s not found", filename)
	}
}

func main() {
	filename := "config.txt"
	
	// Call the openFile function
	err := openFile(filename)
	
	// TODO: Check if err is not nil (which means there was an error)
	// If there was an error, print: "Error: " followed by the error message
	// If there was no error, print: "File opened successfully"
	
}
quiz iconTest yourself

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

All lessons in Fundamentals