The Concept of Errors
Part of the Fundamentals section of Coddy's GO journey — lesson 102 of 109.
In Go, errors are values that indicate something went wrong. Go handles errors explicitly rather than using exceptions.
Let's create a function that might produce an error when dividing numbers:
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}This function returns two values: the result of division and a potential error. If the divisor is zero, we return an error message instead of attempting the division.
Now, let's use our function and handle any potential errors:
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}After executing this code, we'll see an error message on the screen because we tried to divide by zero:
Error: cannot divide by zeroThis demonstrates Go's error handling pattern: check if an error occurred (err != nil), and then take appropriate action. If no error occurred, we can safely use the result.
Challenge
EasyIn this challenge, you'll practice working with errors in Go. You'll create a function that divides two numbers and returns an error if division by zero is attempted.
Your task is to:
- Complete the
dividefunction that takes two integers and returns their quotient and an error. - If the divisor is zero, return 0 and an error with the message "division by zero".
- If the division is valid, return the result and
nilfor the error. - In the
mainfunction, calldividewith the provided values and handle any errors appropriately.
This exercise demonstrates how Go functions commonly return a result and an error, and how to check and handle those errors.
Cheat sheet
In Go, errors are values that indicate something went wrong. Go handles errors explicitly rather than using exceptions.
Functions that might fail return two values: the result and a potential error:
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}To handle errors, check if the error is not nil:
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}Use errors.New() to create new error messages and return nil when no error occurs.
Try it yourself
package main
import (
"errors"
"fmt"
)
// divide divides a by b and returns the result
// If b is 0, it returns an error
func divide(a, b int) (int, error) {
// TODO: Implement the divide function
// If b is 0, return 0 and an error with message "division by zero"
// Otherwise, return a/b and nil for the error
}
func main() {
// First test case
a, b := 10, 2
result, err := divide(a, b)
if err != nil {
fmt.Printf("Error: %s\n", err)
} else {
fmt.Printf("Result: %d\n", result)
}
// Second test case
a, b = 8, 0
result, err = divide(a, b)
if err != nil {
fmt.Printf("Error: %s\n", err)
} else {
fmt.Printf("Result: %d\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