Go Program to Use Panic and Recover

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 recover to 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

  1. Import the Necessary Packages: Use import "fmt" to handle formatted I/O.
  2. 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.
  3. Use defer and recover to Handle the Panic: In another function, use defer and recover to handle the panic and recover from it.
  4. Call the Functions in the Main Function: Use the functions to demonstrate the use of panic and recover.
  5. Display the Result: Use fmt.Println to 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 divide function checks if the denominator b is zero.
    • If b is zero, it triggers a panic using panic("division by zero").
    • Otherwise, it returns the result of the division.

Step 3: Use defer and recover to Handle the Panic

  • The safeDivide function wraps the divide function to handle potential panics.
    • It uses defer to set up a deferred function that calls recover.
    • If recover catches a panic, it returns the error message and allows the program to continue running.

Step 4: Call the Functions in the Main Function

  • The main function 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, but recover catches 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top