In Go, a panic is a runtime error that occurs when a program cannot proceed due to an unexpected condition. When a panic occurs, Go runtime stops normal execution of the program and starts unwinding the stack, which means that it starts to go back through the function call stack and clear out any unrecovered resources until it reaches the main function.
However, we can recover from panic using recover() function. recover() function can only be called in a deferred function, and it returns the value passed to the call to panic(). If the defer function containing recover() is called within the scope of a panicked function, recover() stops the panic and returns the error value that caused the panic.
Here's an example of how to use recover() to handle a panic:
main.go467 chars25 lines
In the example above, we define performDivision() function that can panic if the divisor is zero. We defer a function that contains the recover() call. When the panic occurs, the recover() function is called, and the error is caught and returned as an error instead. This allows us to handle the panic gracefully and return an error instead of letting the panic crash the program.
gistlibby LogSnag