0
0
Goprogramming~30 mins

Handling errors in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling errors
📖 Scenario: You are writing a small program that divides numbers. Sometimes, the divisor might be zero, which causes an error. You want to handle this error properly so the program does not crash and shows a friendly message.
🎯 Goal: Build a Go program that divides two numbers and handles the error when dividing by zero.
📋 What You'll Learn
Create two variables for dividend and divisor
Create a function that divides two numbers and returns an error if divisor is zero
Call the function and handle the error using an if statement
Print the result if no error, or print the error message
💡 Why This Matters
🌍 Real World
Handling errors is important in real programs to avoid crashes and provide clear messages to users.
💼 Career
Error handling is a fundamental skill for software developers to write reliable and user-friendly applications.
Progress0 / 4 steps
1
Create variables for dividend and divisor
Create two variables called dividend and divisor with values 10 and 0 respectively.
Go
Hint

Use var keyword to declare variables with their types and values.

2
Create a divide function that returns error
Create a function called divide that takes two int parameters named a and b. It returns two values: int and error. If b is zero, return zero and an error created with fmt.Errorf("cannot divide by zero"). Otherwise, return the division result and nil error.
Go
Hint

Use fmt.Errorf to create an error message.

3
Call divide function and handle error
In main, call divide(dividend, divisor) and assign the results to variables result and err. Use an if statement to check if err is not nil. If so, print the error message using fmt.Println(err). Otherwise, print the result using fmt.Println(result).
Go
Hint

Use if err != nil to check for errors.

4
Print the final output
Run the program and observe the output. It should print the error message cannot divide by zero because the divisor is zero.
Go
Hint

The program should print the error message because dividing by zero is not allowed.