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 zeroThis 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
EasyIn 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)
}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