In Go, panic
is a built-in function that is used to cause a program to stop execution abruptly. When a panic
occurs, it immediately stops the normal execution flow and starts unwinding the stack, executing any deferred functions along the way until it reaches the top of the goroutine’s stack. At that point, the program terminates and prints a stack trace.
Here’s an example that demonstrates the usage of panic
:
package main
import "fmt"
func main() {
fmt.Println("Start of main")
panic("Something went wrong!")
fmt.Println("End of main") // This line will not be executed
}
In this example, the program starts by printing “Start of main”. However, a panic
is triggered with the message “Something went wrong!”. Since panic
immediately stops the execution flow, the subsequent line fmt.Println("End of main")
is never executed.
When a panic
occurs, the program terminates and prints a stack trace, indicating the line where the panic
was triggered and the sequence of function calls that led to it.
Here’s an example of a panic occurring within a function:
package main
import "fmt"
func doSomething() {
fmt.Println("Doing something...")
panic("Oops! Panic occurred!")
}
func main() {
fmt.Println("Start of main")
doSomething()
fmt.Println("End of main") // This line will not be executed
}
In this example, the doSomething
function triggers a panic
with the message “Oops! Panic occurred!”. When doSomething
is called within the main
function, it causes a panic, and the program terminates without reaching the subsequent line.
Panic is typically used to handle exceptional or unrecoverable errors. It is recommended to use panic sparingly and for situations where it is not possible or reasonable to recover from the error. Instead of relying on panic for normal error handling, Go encourages the use of explicit error values and the error
interface.
To recover from a panic and allow the program to continue execution, you can use the recover
function in combination with a deferred function. However, this should be used judiciously and only in specific scenarios where recovery is possible and necessary.
It’s important to note that the panic
and recover
mechanism should not be used as a general exception handling mechanism in Go. It is designed for exceptional cases and is not intended to be used for regular control flow or error handling.