Home > Backend Development > Golang > panic and recovery in Golang exception handling

panic and recovery in Golang exception handling

WBOY
Release: 2024-04-15 18:15:02
Original
402 people have browsed it

In Go, Panic and Recover are used for exception handling. Panic is used to report exceptions, and Recover is used to recover from exceptions. Panic will stop program execution and throw an exception value of type interface{}. Recover can catch an exception from a deferred function or goroutine, returning the exception value of type interface{} it throws.

panic and recovery in Golang exception handling

Panic and Recover in Go language exception handling

In Go language, panic andrecover The keyword is an important mechanism for exception handling. panic is used to report exceptions, while recover is used to recover from exceptions.

Panic

panic keyword is used to report an exception condition, which will immediately stop program execution and print stack information. When using panic, the program will throw an exception value of type interface{}. For example:

package main

func main() {
    panic("发生了异常")
}
Copy after login

Recover

recover keyword is used to recover from panic. It can return an exception value of type interface{} from the current goroutine. recover can only be used within deferred functions or goroutines. For example:

package main

import "fmt"

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("捕获到异常:", r)
        }
    }()
    panic("发生了异常")
}
Copy after login

Practical case

Suppose we have a function divide, which calculates the quotient of two numbers:

func divide(a, b int) float64 {
    if b == 0 {
        panic("除数不能为零")
    }
    return float64(a) / float64(b)
}
Copy after login

In order to handle exceptions that may occur in the divide function, we can use recover Keywords:

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("捕获到异常:", r)
        }
    }()

    fmt.Println(divide(10, 2))
    fmt.Println(divide(10, 0))
}
Copy after login

Output:

5
捕获到异常: 除数不能为零
Copy after login

The above is the detailed content of panic and recovery in Golang exception handling. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template