0
0
Goprogramming~15 mins

Why error handling is required in Go - See It in Action

Choose your learning style9 modes available
Why error handling is required
📖 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.