Introduction
In Go, panic and recover are built-in functions that provide a way to handle unexpected situations and recover from panics, respectively. panic is used to stop the normal flow of control and start panicking, which means the program will start unwinding the stack until it crashes or recovers. recover is used to regain control of the program after a panic has occurred.
This guide will demonstrate how to use panic and recover in Go.
Problem Statement
Create a Go program that:
- Triggers a panic in certain situations.
- Uses
recoverto handle the panic and prevent the program from crashing. - Displays appropriate messages based on whether the panic was handled or not.
Example:
- Operation: Division by zero.
- Output:
Error: division by zero Program continued execution.
Solution Steps
- Import the Necessary Packages: Use
import "fmt"to handle formatted I/O. - Write a Function that Triggers a Panic: Implement a function that performs a risky operation, such as division, and triggers a panic if an error occurs.
- Use
deferandrecoverto Handle the Panic: In another function, usedeferandrecoverto handle the panic and recover from it. - Call the Functions in the Main Function: Use the functions to demonstrate the use of
panicandrecover. - Display the Result: Use
fmt.Printlnto display messages based on whether the panic was handled or not.
Go Program
package main
import (
"fmt"
)
// Step 2: Implement a function that triggers a panic
func divide(a, b int) int {
if b == 0 {
panic("division by zero") // Trigger a panic if dividing by zero
}
return a / b
}
// Step 3: Use defer and recover to handle the panic
func safeDivide(a, b int) (result int) {
// Defer a function that will handle the panic
defer func() {
if r := recover(); r != nil {
fmt.Println("Error:", r)
}
}()
// Perform the division
result = divide(a, b)
return
}
/**
* Go Program to Use Panic and Recover
* Author: https://www.javaguides.net/
*/
func main() {
// Step 4: Call the functions to demonstrate panic and recover
fmt.Println("Attempting to divide 10 by 2:")
result := safeDivide(10, 2)
fmt.Println("Result:", result)
fmt.Println("\nAttempting to divide 10 by 0:")
result = safeDivide(10, 0) // This will cause a panic
fmt.Println("Result:", result)
fmt.Println("\nProgram continued execution.")
}
Explanation
Step 2: Implement a Function that Triggers a Panic
- The
dividefunction checks if the denominatorbis zero.- If
bis zero, it triggers a panic usingpanic("division by zero"). - Otherwise, it returns the result of the division.
- If
Step 3: Use defer and recover to Handle the Panic
- The
safeDividefunction wraps thedividefunction to handle potential panics.- It uses
deferto set up a deferred function that callsrecover. - If
recovercatches a panic, it returns the error message and allows the program to continue running.
- It uses
Step 4: Call the Functions in the Main Function
- The
mainfunction demonstrates both a successful division and a division by zero, showing how the program recovers from the panic.
Step 5: Display the Result
- The program prints the result of the division if successful, or an error message if a panic occurred. The final message confirms that the program continues to execute even after a panic.
Output Example
Example Output:
Attempting to divide 10 by 2:
Result: 5
Attempting to divide 10 by 0:
Error: division by zero
Result: 0
Program continued execution.
Example Explanation:
- The first division (
10 / 2) succeeds, so the result is printed. - The second division (
10 / 0) causes a panic, butrecovercatches it and prints an error message instead of crashing the program. - The program continues running after handling the panic.
Conclusion
This Go program demonstrates how to use panic and recover to handle unexpected situations gracefully. It covers basic concepts such as triggering panics, recovering from them, and ensuring that the program continues running. This example is useful for beginners learning Go programming and understanding how to manage errors and exceptions effectively.