0
0
Goprogramming~15 mins

Returning errors in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Returning errors
📖 Scenario: You are writing a simple program to check if a number is positive. If the number is not positive, you want to return an error message.
🎯 Goal: Build a Go program that defines a function to check if a number is positive and returns an error if it is not. Then call this function and handle the error properly.
📋 What You'll Learn
Create a function that returns an error when the input number is not positive
Use the built-in errors.New function to create the error
Call the function with a negative number to test error handling
Print the error message if an error is returned
💡 Why This Matters
🌍 Real World
Returning errors is important in real programs to handle unexpected situations like invalid input or failed operations.
💼 Career
Understanding how to return and handle errors is a key skill for Go developers working on reliable and maintainable software.
Progress0 / 4 steps
1
Create a function to check if a number is positive
Write a function called checkPositive that takes an int parameter named num and returns an error. The function should return nil for now.
Go
Hint

Define the function with the correct name, parameter, and return type. Return nil to indicate no error.

2
Add error return for non-positive numbers
Modify the checkPositive function to return an error using errors.New with the message "number is not positive" if num is less than or equal to zero. Otherwise, return nil. Remember to import the errors package.
Go
Hint

Use an if statement to check the number and return the error with errors.New.

3
Call the function and handle the error
In the main function, call checkPositive with the value -5 and store the result in a variable called err. Use an if statement to check if err is not nil.
Go
Hint

Call the function with -5 and check if the returned error is not nil.

4
Print the error message
Inside the if err != nil block, use fmt.Println(err) to print the error message. Remember to import the fmt package.
Go
Hint

Use fmt.Println(err) to show the error message on the screen.