search
HomeBackend DevelopmentGolangIntroduction to exception handling in go language

Introduction to exception handling in go language

Nov 27, 2019 pm 03:57 PM
go language

Introduction to exception handling in go language

Go language pursues simplicity and elegance, so Go language does not support the traditional try...catch...finally exception, because the designers of Go language believe that, Mixing exceptions with control structures can easily clutter your code.

Because developers can easily abuse exceptions, throwing an exception even for a small mistake. In Go language, multiple values ​​are used to return errors. Don't use exceptions to replace errors, let alone control the process. In rare cases, that is, when a real exception is encountered (such as the divisor is 0). Only use the Exception handling introduced in Go: defer, panic, recover.

The usage scenarios of these exceptions can be described simply: Go can throw a panic exception, then capture the exception through recover in defer, and then handle it normally.

Example code:

package main
 
import "fmt"
 
func main(){
    defer func(){ // 必须要先声明defer,否则不能捕获到panic异常
        fmt.Println("c")
        if err:=recover();err!=nil{
            fmt.Println(err) // 这里的err其实就是panic传入的内容,55
        }
        fmt.Println("d")
    }()
    f()
}
 
func f(){
    fmt.Println("a")
    panic(55)
    fmt.Println("b")
    fmt.Println("f")
}

Output result:

a
c
55
d
exit code 0, process exited normally.

defer

defer Original English meaning: vi. To postpone; to postpone; to obey vt. To postpone; to postpone.

The idea of ​​defer is similar to the destructor in C, but in the Go language, what is "destructed" is not the object, but the function. Defer is used to add statements that are executed when the function ends. Note that the emphasis here is on adding, not specifying, because unlike the destructor in C which is static, the defer in Go is dynamic.

func f() (result int) {
  defer func() {
    result++
  }()
  return 0
}

The above function returns 1 because a function is added to defer and the value of the named return value is changed before the function returns. Isn’t it very useful? However, it should be noted that if our defer statement is not executed, the defer function will not be added. If the above program is changed to this:

func f() (result int) {
  return 0
  defer func() {
    result++
  }()
  return 0
}

The above function will return 0, because there is still The function returned before I had time to add defer.

It is also worth mentioning that defer can be performed multiple times, thus forming a defer stack, and the subsequent defer statements will be called first when the function returns.

panic

##panic Original English meaning: n. Panic, panic; panic adj. Panic; no reason vt. To panic vi . Very panic

panic is used to indicate a very serious and unrecoverable error. In the Go language, this is a built-in function that receives a value of type interface{} (that is, any value) as a parameter. The function of panic is just like the exceptions we usually come into contact with. However, Go does not have try...catch, so panic will generally cause the program to hang (unless it is recovered). Therefore, exceptions in the Go language are really exceptions. You can try calling panic to see if the program hangs immediately, and then the call stack will be printed out when Go is running.

However, the key point is that even if the function panics when it is executed, the function does not go down. The panic is not immediately passed upward during runtime, but to defer. When all the things in defer are finished, panic will occur again. Pass upward. So at this time defer is somewhat similar to finally in try-catch-finally.
panic is that simple. Throw a real exception.

recover

recover Original English meaning: vt. to recover; to make up for; to regain vi. to recover; to win; to regain the ball n. to restore to Preparatory posture

As mentioned above, the panic function does not return immediately, but defers first and then returns. At this time (during defer), if there is a way to capture the panic and prevent the panic from being delivered, then the exception handling mechanism will be perfect.

Go language provides the recover built-in function. As mentioned earlier, once panic occurs, the logic will go to defer, then we will wait at defer. Calling the recover function will capture the current panic (if If so), the captured panic will not be passed upwards, and peace will be restored to the world. You can do what you want.

However, it should be noted that after recovery, the logic will not be restored to the panic point, and the function will still return after defer.

Conclusion:

Go's attitude towards exceptions (panic to be precise) is this. It does not completely deny the existence of exceptions, and at the same time, it strongly discourages the use of exceptions.

The above is the detailed content of Introduction to exception handling in go language. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Is Golang Faster Than C  ? Exploring the LimitsIs Golang Faster Than C ? Exploring the LimitsApr 20, 2025 am 12:19 AM

Golang performs better in compilation time and concurrent processing, while C has more advantages in running speed and memory management. 1.Golang has fast compilation speed and is suitable for rapid development. 2.C runs fast and is suitable for performance-critical applications. 3. Golang is simple and efficient in concurrent processing, suitable for concurrent programming. 4.C Manual memory management provides higher performance, but increases development complexity.

Golang: From Web Services to System ProgrammingGolang: From Web Services to System ProgrammingApr 20, 2025 am 12:18 AM

Golang's application in web services and system programming is mainly reflected in its simplicity, efficiency and concurrency. 1) In web services, Golang supports the creation of high-performance web applications and APIs through powerful HTTP libraries and concurrent processing capabilities. 2) In system programming, Golang uses features close to hardware and compatibility with C language to be suitable for operating system development and embedded systems.

Golang vs. C  : Benchmarks and Real-World PerformanceGolang vs. C : Benchmarks and Real-World PerformanceApr 20, 2025 am 12:18 AM

Golang and C have their own advantages and disadvantages in performance comparison: 1. Golang is suitable for high concurrency and rapid development, but garbage collection may affect performance; 2.C provides higher performance and hardware control, but has high development complexity. When making a choice, you need to consider project requirements and team skills in a comprehensive way.

Golang vs. Python: A Comparative AnalysisGolang vs. Python: A Comparative AnalysisApr 20, 2025 am 12:17 AM

Golang is suitable for high-performance and concurrent programming scenarios, while Python is suitable for rapid development and data processing. 1.Golang emphasizes simplicity and efficiency, and is suitable for back-end services and microservices. 2. Python is known for its concise syntax and rich libraries, suitable for data science and machine learning.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools