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