0
0
Goprogramming~20 mins

Recover usage in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Recover Usage in Go
📖 Scenario: Imagine you are writing a Go program that divides two numbers. Sometimes, the divisor might be zero, which causes a program crash. You want to handle this problem gracefully so the program doesn't stop unexpectedly.
🎯 Goal: You will build a Go program that uses recover inside a deferred function to catch a panic caused by division by zero and print a friendly error message instead of crashing.
📋 What You'll Learn
Create a function called divide that takes two integers a and b and returns an integer result.
Inside divide, use defer with an anonymous function that calls recover() to catch panics.
If a panic occurs, print "Recovered from panic: division by zero".
In divide, perform the division a / b which will panic if b is zero.
Call divide twice in main: once with 10 and 2, and once with 10 and 0.
Print the result of the division when no panic occurs.
💡 Why This Matters
🌍 Real World
Handling unexpected errors like division by zero is important in real-world programs to avoid crashes and provide better user experience.
💼 Career
Understanding panic and recover is useful for Go developers to write robust and fault-tolerant applications.
Progress0 / 4 steps
1
Create the divide function with parameters
Write a function called divide that takes two integer parameters a and b and returns an integer.
Go
Hint

Start by writing the function header with the correct name and parameters.

2
Add defer with recover to catch panics
Inside the divide function, add a defer statement with an anonymous function that calls recover(). If recover() returns a non-nil value, print "Recovered from panic: division by zero".
Go
Hint

Use defer func() { if r := recover(); r != nil { ... } }() to catch panics.

3
Perform division that may panic
In the divide function, replace the return 0 with return a / b to perform the division that may cause a panic if b is zero.
Go
Hint

Replace the return statement with the division expression a / b.

4
Call divide in main and print results
Write a main function that calls divide(10, 2) and prints the result, then calls divide(10, 0) to show the recovered panic message.
Go
Hint

Call divide(10, 2), print the result, then call divide(10, 0) to trigger and recover from panic.