SoFunction
Updated on 2025-03-04

Various scenarios and practical techniques for unknown exception capture in Go language

1. Preface

In Go programming, exception handling is a key link in ensuring the robustness of the program. Unlike some other programming languages, Go does not have traditionaltry - catchStructured exception handling mechanism. However, it providesdeferandrecoverThis powerful combination of pairs handles runtime panics, thereby enabling effective capture and handling of unknown exceptions. This article will explore in-depth various scenarios and practical techniques for unknown exception capture in Go language.

2. Basic usage of defer and recover

In Go,deferKeywords are used to delay execution of a function or statement block until the function containing it is about to return. andrecoverFunctions are specifically used for capturepanicThe outlier value thrown.

Here is a simple example code:

package main

import "fmt"

func main() {
    defer func() {
        if r := recover(); r!= nil {
            ("Recovered from panic:", r)
        }
    }()
    // This caused a panic    panic("Something went wrong")
}

In the above code,mainFunctions are first useddeferAn anonymous function is defined. whenmainThe function is executed topanicWhen a statement is made, the program will panic. At this time, becausedeferThe delayed execution feature of anonymous functions will be called.recoverThe function tries to catch panic inside anonymous function. If the capture is successful (i.e.recoverThe returned value is notnil), and the relevant panic information is printed out.

3. Exception capture in multiple goroutines

When multiplegoroutineWhen catching exceptions need to be paid special attention torecoverOnly currently availablegoroutineThe delay function plays a role.

Consider the following example:

package main

import (
    "fmt"
    "sync"
)

func worker() {
    defer func() {
        if r := recover(); r!= nil {
            ("Worker recovered from panic:", r)
        }
    }()
    panic("Worker panic")
}

func main() {
    var wg 
    (1)
    go func() {
        defer ()
        worker()
    }()
    ()
}

In this example,workerFunctions in a separategoroutineRun in.workerInternal use of functionsdeferandrecoverto capture the panic that you may have. existmainIn the function,WaitGroupCome and make suregoroutineExecution is completed. whenworkerWhen a function panics,recoverWill be hereworkerFunctionaldeferCapture it in the function and output the corresponding information.

4. Exception transmission in function call chain

In the function call chain, sometimes it is necessary to pass the exceptions of the underlying function to the upper function for unified processing.

Here is a sample code showing how to pass exceptions in a function call chain:

package main

import "fmt"

func lowerLevel() error {
    defer func() {
        if r := recover(); r!= nil {
            ("Lower level recovered from panic:", r)
            // You can choose to convert panic to error and return            err, ok := r.(error)
            if ok {
                ("Returning error:", err)
                // Assuming there is a suitable error return mechanism here, a simple return here                // More complex error handling logic may be required in actual applications                return
            }
        }
    }()
    panic(("Lower level panic"))
    return nil
}

func higherLevel() {
    if err := lowerLevel(); err!= nil {
        ("Higher level handling error:", err)
    }
}

func main() {
    higherLevel()
}

In the above code,lowerLevelA panic occurs inside the function. existdeferAfter catching panic in the function, try to convert it toerrortype. If the conversion is successful,lowerLevelThe function can return this error tohigherLevelfunction, thenhigherLevelThe function can handle this error.

5. Handle exceptions caused by external libraries

When external libraries are called, these libraries can cause panic. We can also use the helpdeferandrecoverTo handle this situation.

For example, suppose there is a third-party librarythird_party_lib, among themSomeFunctionThatMayPanicFunctions may cause panic:

package main

import (
    "fmt"
    "third_party_lib"
)

func callThirdParty() {
    defer func() {
        if r := recover(); r!= nil {
            ("Recovered from third - party panic:", r)
        }
    }()
    third_party_lib.SomeFunctionThatMayPanic()
}

func main() {
    callThirdParty()
}

existcallThirdPartyIn the function, usedeferandrecoverto catch panic that may be caused by third-party library functions, thereby preventing the program from crashing due to exceptions in external libraries.

6. Summary

Although Go language does not have traditionaltry - catchException handling structure, but throughdeferandrecoverThe clever combination of unknown exceptions can be effectively caught and handled in a variety of scenarios. Whether it is on the singlegoroutineEnvironment, manygoroutineCollaboration, function call chain pass and handling external library exceptions, rational use of these mechanisms can greatly improve the stability and robustness of the program, allowing developers to better deal with various possible runtime errors.

The above is the detailed content of various scenarios and practical techniques for unknown exception capture in Go. For more information about unknown exception capture in Go, please pay attention to my other related articles!