panic() and recover() are two important functions in the Go language for handling exceptions. Here is a simple example that demonstrates how to use panic() and recover() in Go.
1 | package main |
In the example above, the doSomething() function attempts to divide 10 by 0, which would lead to a division by zero panic. However, we use defer() and recover() to catch and handle the panic. In the main() function, even if a panic occurs within doSomething(), the program continues to execute, and the panic information is printed within the recover() block.
Running this program will produce the following output:
1 | Starting the program |
This demonstrates that the recover() function successfully catches the panic, allowing the program to continue executing without terminating.”