📖 Scenario: Imagine you are writing a program that reads numbers from a list and divides 100 by each number. Sometimes, the number might be zero, which causes a problem called a "division by zero" error. To keep the program running smoothly, you need to handle such errors.
🎯 Goal: Build a simple Go program that divides 100 by numbers in a list and handles the error when division by zero happens.
📋 What You'll Learn
Create a slice of integers called numbers with the values 10, 5, 0, 2
Create a variable called result to store the division result
Use a for loop with variable num to iterate over numbers
Inside the loop, check if num is zero and handle the error by printing "Cannot divide by zero"
If no error, calculate result = 100 / num and print the result
The program should continue running even if an error occurs
💡 Why This Matters
🌍 Real World
Programs often get unexpected inputs or face problems like missing files or network issues. Error handling helps manage these situations gracefully.
💼 Career
Understanding error handling is essential for writing reliable software, a key skill for any software developer or engineer.
Progress0 / 4 steps
1
Create the list of numbers
Create a slice of integers called numbers with the values 10, 5, 0, and 2.
Go
Hint
Use numbers := []int{10, 5, 0, 2} to create the slice.
2
Add a variable for the result
Add a variable called result of type int to store the division result inside the main function, after creating numbers.
Go
Hint
Use var result int to declare the variable.
3
Loop through numbers and handle division by zero
Use a for loop with variable num to iterate over numbers. Inside the loop, check if num is zero. If it is, print "Cannot divide by zero". Otherwise, calculate result = 100 / num.
Go
Hint
Use for _, num := range numbers to loop. Use if num == 0 to check zero.
4
Print the results and errors
Make sure the program prints the division results or the error message for each number in numbers. Run the program to see the output.
Go
Hint
Run the program and check the printed lines match the expected output.
Practice
(1/5)
1. Why is error handling important in Go programs?
easy
A. It makes the program run faster by skipping checks.
B. It removes the need to write any tests.
C. It automatically fixes all bugs in the code.
D. It helps the program continue running even when something unexpected happens.
Solution
Step 1: Understand the role of error handling
Error handling is used to manage unexpected problems during program execution.
Step 2: Identify the benefit in Go programs
By handling errors, the program can avoid crashing and continue working smoothly.
Final Answer:
It helps the program continue running even when something unexpected happens. -> Option D
Quick Check:
Error handling = program stability [OK]
Hint: Error handling keeps programs stable during problems [OK]
Common Mistakes:
Thinking error handling speeds up code
Believing error handling fixes bugs automatically
Assuming error handling removes need for testing
2. Which of the following is the correct way to check an error returned by a function in Go?
easy
A. if err = nil { // handle error }
B. if err != nil { // handle error }
C. if error != nil { // handle error }
D. if err == nil { // handle error }
Solution
Step 1: Recall Go error checking syntax
In Go, errors are checked by comparing the error variable to nil.
Step 2: Identify correct syntax
The correct check is if err != nil, meaning an error occurred.
Final Answer:
if err != nil { // handle error } -> Option B
Quick Check:
Check error with '!= nil' [OK]
Hint: Always check if err is NOT nil to catch errors [OK]
Common Mistakes:
Using '==' instead of '!=' to check errors
Using wrong variable name like 'error'
Assigning instead of comparing with '='
3. What will be the output of this Go code snippet?
package main
import (
"errors"
"fmt"
)
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(result)
}
}
medium
A. cannot divide by zero
B. 0
C. 10
D. runtime error
Solution
Step 1: Analyze the divide function call
divide(10, 0) checks if b is zero, which it is, so it returns an error with message "cannot divide by zero".
Step 2: Check main function error handling
Since err is not nil, the program prints the error message instead of the result.
Final Answer:
cannot divide by zero -> Option A
Quick Check:
Error message printed when dividing by zero [OK]
Hint: Error returned when dividing by zero prints message [OK]
Common Mistakes:
Expecting 0 as output instead of error message
Ignoring error and printing result
Assuming runtime panic occurs
4. Identify the error in this Go code snippet related to error handling:
package main
import "fmt"
func openFile(name string) error {
// pretend to open file
return nil
}
func main() {
err := openFile("data.txt")
if err == nil {
fmt.Println("Error opening file")
} else {
fmt.Println("File opened successfully")
}
}
medium
A. The variable err is not declared properly.
B. The function openFile should return a string, not error.
C. The error check condition is reversed; it should be 'if err != nil'.
D. The fmt package is not imported.
Solution
Step 1: Review error check logic in main
The code checks if err == nil to print an error message, which is incorrect logic.
Step 2: Correct error check condition
It should check if err != nil to detect an error and print the error message.
Final Answer:
The error check condition is reversed; it should be 'if err != nil'. -> Option C
Quick Check:
Error check must be '!= nil' to catch errors [OK]
Hint: Error means err != nil, not err == nil [OK]
Common Mistakes:
Checking err == nil to detect errors
Confusing error return types
Ignoring error handling completely
5. You want to read a file and print its contents in Go. Why should you handle errors returned by the file reading function?
hard
A. Because the file might not exist or be unreadable, causing the program to fail without error handling.
B. Because handling errors makes the file read faster.
C. Because Go requires all functions to return errors even if they never happen.
D. Because error handling automatically fixes missing files.
Solution
Step 1: Understand file reading risks
Files may not exist, be locked, or have permission issues, causing errors when reading.
Step 2: Importance of error handling
Handling errors lets the program respond gracefully instead of crashing or producing wrong output.
Final Answer:
Because the file might not exist or be unreadable, causing the program to fail without error handling. -> Option A
Quick Check:
Handle file errors to avoid crashes [OK]
Hint: Always check file read errors to avoid crashes [OK]