errors.New function to create the errorReturning errors in Go - Mini Project: Build & Apply
checkPositive that takes an int parameter named num and returns an error. The function should return nil for now.Define the function with the correct name, parameter, and return type. Return nil to indicate no error.
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.Use an if statement to check the number and return the error with errors.New.
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.Call the function with -5 and check if the returned error is not nil.
if err != nil block, use fmt.Println(err) to print the error message. Remember to import the fmt package.Use fmt.Println(err) to show the error message on the screen.
Practice
What does a Go function return when there is no error?
Solution
Step 1: Understand Go error convention
In Go, functions return an error type to indicate problems. If no problem occurs, the error isnil.Step 2: Identify the correct no-error return value
The standard way to show no error is to returnnil, not zero, empty string, or text.Final Answer:
It returnsnilas the error value. -> Option AQuick Check:
No error means error = nil [OK]
- Returning 0 instead of nil for no error
- Returning empty string instead of nil
- Returning a string message instead of nil
Which of the following is the correct way to declare a Go function that returns an int and an error?
func example() ???
Solution
Step 1: Recall Go function return syntax
Go functions return multiple values by listing types in parentheses separated by commas.Step 2: Match correct syntax
The correct syntax for returning an int and error is(int, error). Other options miss commas or parentheses.Final Answer:
func example() (int, error) -> Option AQuick Check:
Multiple returns use parentheses and commas [OK]
- Omitting parentheses for multiple returns
- Missing comma between return types
- Writing return types without parentheses
What will be the output of this Go program?
package main
import (
"errors"
"fmt"
)
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(result)
}
}Solution
Step 1: Analyze divide function behavior
If divisorbis zero, function returns error with message "division by zero" and result 0.Step 2: Check main function output
Main calls divide(10, 0), gets error != nil, so prints the error message.Final Answer:
division by zero -> Option BQuick Check:
Error returned prints message [OK]
- Printing result even when error is not nil
- Expecting 0 as output instead of error message
- Assuming runtime panic on division by zero
Identify the error in this Go function that returns an error:
func readFile(name string) (string, error) {
data := ""
file, err := os.Open(name)
if err != nil {
return data, err
}
defer file.Close()
// read file content
return data, nil
}Solution
Step 1: Check for required imports
The function usesos.Openbut does not importospackage, causing a compile error.Step 2: Verify other code parts
Return types and defer placement are correct; only missing import is the problem.Final Answer:
Missing import ofospackage. -> Option DQuick Check:
Using os.Open requires importing os [OK]
- Forgetting to import packages used
- Placing defer before error check
- Returning wrong number of values
You want to write a Go function parseNumber that takes a string and returns an int and an error. It should return an error if the string is empty or not a valid number. Which implementation correctly returns errors?
func parseNumber(s string) (int, error) {
if s == "" {
return 0, errors.New("empty input")
}
n, err := strconv.Atoi(s)
if err != nil {
return 0, err
}
return n, nil
}Solution
Step 1: Check empty string error handling
The function returns error "empty input" if string is empty, which is correct.Step 2: Check invalid number error handling
Usesstrconv.Atoito convert string; returns error if conversion fails.Step 3: Confirm success return
If no error, returns parsed number andnilerror.Final Answer:
Correctly returns errors for empty and invalid input. -> Option CQuick Check:
Empty and invalid inputs return errors [OK]
- Not checking empty string before conversion
- Ignoring error from strconv.Atoi
- Returning nil error on invalid input
Ready to prove it?
Pass the test and this pattern moves unknown
