SoFunction
Updated on 2025-03-05

Detailed explanation of the usage of Go language exception handling (Panic and recovery)

Basic syntax

Exception handling is the key to program robustness, and the development experience of developers can often be reflected in the exception part processing. How to moderately add abnormalities is often the key to the success or failure of the entire product experience.

There is no Try Catch Exception mechanism in Go, but a panic-and-recover mechanism is provided.

Panic

Built-in function panic()

Similar to raise, it can stop normal processes

When panic is called in the function, the normal process will be terminated and the defer function will still be executed

The reason for Panic can be an active call or a runtime error, such as array out of bounds

Recover

Built-in function for handling panic(panicking goroutine)

It makes sense to use in defer function. During normal execution, recover will only return nil, and there are no other side effects

If the current Goroutine (will be explained later when concurrency is discussed, it will be understood as the execution process of the program) panicking occurs, the panic value will be automatically captured to recover, and normal execution will be restored at the same time

Example 1: How to use recover()

This example mainly illustrates how to catch exceptions. Let’s first simulate an exception. In some projects, there are often cases where array subscripts cross boundaries. Let’s construct it artificially.

package main

import "fmt"

func MyPanic() {
    ("Running in MyPanic...")
    var a[]int
    a[3] = 5
}

func main() {
    MyPanic()
}

When running the program at this time, it is obvious that the following problems will occur:

Running in MyPanic...
panic: runtime error: index out of range [3] with length 0

goroutine 1 [running]:
()
    /root/workspace/go/test_panic_recover_basic.go:14 +0x5e
()
    /root/workspace/go/test_panic_recover_basic.go:18 +0x17
exit status 2

Try to use recover for exception handling

package main

import "fmt"

func MyPanic() {
    defer func() {
        if x := recover(); x != nil {
            ("[ERROR]: My panic handle error: %s\n", x)
        }
    }()

    ("Running in MyPanic...")
    var a[]int
    a[3] = 5
}

func main() {
    MyPanic()
}

Let’s analyze the above code:

First, a defer function was added

In defer, use x := recover(); x != nil to catch the exception. If the obtained value is not empty, it is proved that an exception has occurred

When obtaining exception information, you can output detailed error information directly using the variable just now. The execution result is as follows

Running in MyPanic...
[ERROR]: My panic handle error: runtime error: index out of range [3] with length 0

Example 2: Panic() usage method

In addition to introducing panic(), this example also implements a unified ErrorHandler method (a bit like a decorator in Python) to handle exceptions of functions uniformly

package main

import "fmt"

func ErrorHandler(f func()) (b bool) {
    defer func() {
        if x := recover(); x != nil {
            ("[ERROR]Handle error here: %s\n", x)
            b = true
        }
    }()
    f()
    return
}

func CallPanic() {
    panic("Call panic")
}

func main() {
    (ErrorHandler(CallPanic))
}

Let's analyze the code:

Define two functions, one is CallPanic() to generate an exception, and the other is ErrorHandler() to capture the exceptions of all functions.

CallPanic() logic is very simple, it is to use the built-in panic() function to generate exceptions. The following parameters are the specific content of the exception.

The parameter of ErrorHandler is a function, that is, the property of the function as a value, and the return value is bool type

The exception capture in ErrorHandler is the same as the example. It is completed using the defer function. In the function body, the called function f() is executed.

Judging from the execution results, the ErrorHandler outputs the Call panic exception and return result true

This is the introduction to this article about the detailed explanation of the usage of Go language exception handling (Panic and recovery). For more related Go language exception handling content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!