SoFunction
Updated on 2025-04-14

Go Simple practice of exception handling panic and recover

panic and recover

Of course, it can trigger the program to be down and exit, or we can also be ourselves. For example, after checking and judging, the current environment cannot meet the expected conditions of our program (for example, a service designated listening port is occupied by other programs), panic can be triggered manually to make the program exit and stop running.

1. Trigger panic

It is very simple to trigger a downtime manually. You only need to call the built-in function panic, just like this

package main

func main() {
    panic("crash")
}

Running results:

panic: crash

goroutine 1 [running]:
()
        d:/Goworks/src/Silicon Valley/Exception handling/:4 +0x25
exit status 2

2. Capture panic

When an exception occurs, sometimes it has to be caught, just like in PythonexceptSimilarly, how did it be done in Golang?

This has to introduce another built-in function –recover, it can make the program resurrect after a downtime.

However, there is a condition for using recover.It must be in the defer function to take effect, under other scopes, it does not work.

Here is a simple example

package main

import "fmt"

func set_data(x int) {
    defer func() {
        // recover() can print the captured panic information        if err := recover(); err != nil {
            (err)
        }
    }()

    // Deliberately create an array to cross the boundary, triggering panic    var arr [10]int
    arr[x] = 88
}

func main() {
    set_data(20)

    // If this sentence can be executed, it means that panic has been captured    // The subsequent programs can continue to run    ("everything is ok")
}

Running results:

It runs normally after capturing panic.

runtime error: index out of range [20] with length 10
everything is ok

3. Cannot cross coroutine

From the above example, we can see that even if panic causes the entire program to exit, if there is a defer delay function before exiting, defer must be executed.

However, this defer has no effect between multiple coroutines. When triggering panic in a child coroutine, it can only trigger the defer in its own coroutine, and cannot call the defer function in the main coroutine.

Just do an experiment and you'll know

package main

import (
    "fmt"
    "time"
)

func main() {
    // This defer will not be executed    defer ("in main")

    go func() {
        defer println("in goroutine")
		// This panic will terminate the program		// If the defer outside is terminated here, it will not be executed.        panic("")
    }()

    (2 * )
}

The output is as follows, and defer ("in main") is not executed

in goroutine
panic:

goroutine 19 [running]:
.func1()
        d:/Goworks/src/Silicon Valley/Exception handling/:14 +0x3e
created by  in goroutine 1
        d:/Goworks/src/Silicon Valley/Exception handling/:12 +0x59
exit status 2

4. Summary

Golang exception throwing and catching rely on two built-in functions:

  • panic: throw an exception, causing the program to crash
  • recover: catch exceptions, restore program or doFinal work(Generally speaking, no processing should be done to programs that enter panic downtime, but sometimes, we need to recover from the downtime. At least we can do some operations before the program crashes. For example, when the web server encounters unpredictable serious problems, all connections should be closed before the crash. If nothing is done, the client will be in a waiting state. If the web server is still in the development stage, the server can even feed the exception information to the client to help debug.)

After the revocer is called, the thrown panic will end here and will not be thrown out again. However, recover cannot be used arbitrarily. It has mandatory requirements and must be used under defer.

This is the article about the simple practice of go exception handling panic and recover. For more related go exception handling panic and recover content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!