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 zeroChallenge
BeginnerIn 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"
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison Operators - Part 1Comparison Operators - Part 2Logical AND OperatorLogical OR OperatorLogical NOT OperatorOperator Precedence BasicsRecap - Making Comparisons7Control Flow: Loops
What The `for` Loop ExplainedFor Loop - BasicFor Loop - Condition OnlyThe `break` KeywordThe `continue` KeywordNested LoopsRecap - Repeating Actions2Variables and Basic Data Types
What is a variableType Inference with `:=`Integers (int)Floating-Point NumbersBooleansStringsZero ValuesConstantsNaming ConventionsRecap - Variables and Types5Basic Input/Output
Formatted OutputFormat VerbsPrinting TypesGetting Basic User InputRecap - Input and Output8Functions
Understanding FunctionsDeclaring a FunctionCalling FunctionsFunction ParametersReturning a Single ValueReturning Multiple ValuesNamed Return ValuesFunction Scope BasicsRecap - Creating Reusable Code11Composite Types: Slices
Introduction to SlicesDeclaring Slice LiteralsCreating Slices with `make`Slice Length vs CapacityAccessing Slice ElementsAppending ElementsSlicing Existing Slices/ArraysIterating Over SlicesCopying SlicesRecap - Dynamic Lists14Basic Error Handling
The Concept of ErrorsThe `error` InterfaceFunctions Returning ErrorsChecking for ErrorsCreating Simple ErrorsCreating Formatted ErrorsBasic Error HandlingRecap - Handling Problems3Basic Operators
Arithmetic OperatorsDivision OperatorThe Modulo OperatorAssignment OperatorAugmented Assignment OperatorsIncrement and DecrementRecap - Calculations6Control Flow: Conditionals
The `if` StatementThe `else` KeywordThe `else if` KeywordVariable Shadowing in `if`Initializing VariablesThe `switch` StatementSwitch with ExpressionsSwitch without ExpressionThe `fallthrough` KeywordRecap - Making Decisions