congdong007

Penetration Test、Software Developer

0%

panic() and recover() in the Go Language

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package main

import (
"fmt"
)

// A function to simulate a situation that might cause a panic
func doSomething() {
defer func() {
if err := recover(); err != nil {
fmt.Println("Panic occurred but recovered:", err)
}
}()

// Simulate a problematic situation
num1 := 10
num2 := 0
result := num1 / num2 // This will cause a division by zero panic
fmt.Println("Result is:", result) // This won't be printed as the panic has already occurred
}

func main() {
fmt.Println("Starting the program")

doSomething()

fmt.Println("Program continues to execute") // Even if a panic occurs, this line will be printed because the panic has been recovered in doSomething()
}

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
2
3
4
Starting the program
Panic occurred but recovered: runtime error: integer divide by zero
Program continues to execute

This demonstrates that the recover() function successfully catches the panic, allowing the program to continue executing without terminating.”