Panic and recover in Go

 Panic and recover in Go


Panic and recover are built-in functions provided by Go for handling errors and panics in a structured way. When a panic occurs, the normal flow of execution is interrupted and the program may terminate. However, using recover, we can catch the panic and handle it gracefully.


Here's an example of using panic and recover:



func doSomething() {

    defer func() {

        if r := recover(); r != nil {

            fmt.Println("recovered from panic:", r)

        }

    }()

    panic("something went wrong")

}


doSomething() // prints "recovered from panic: something went wrong"

In this example, we define a function that panics with a message. We then use a deferred function to recover from the panic and print a message.


The recover function returns the value passed to the panic function, allowing us to inspect the error and take appropriate action.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...