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

panic and recovery in Golang exception handling

WBOY
WBOYOriginal
2024-04-15 18:15:02328browse

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("发生了异常")
}

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("发生了异常")
}

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)
}

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))
}

Output:

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

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!

Statement:
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