Go error handling


Go error handling

  • Error type is an interface type. This is its definition:
    type error interface {
      Error() string

Go catch exception

Traditional methods of catching exceptions


Go language

Defer, panic and recover are introduced
1. Go program throws a panic exception, catches the exception through recover in defer, and then handles it


package main
import "fmt"
func test() {
    //Execute defer before the function exits
    //After catching an exception, the program will not exit abnormally
    defer func() {
        Err: = recover() // built in function, which can catch function exceptions
        if err != nil {
            //This is a printing error, and you can also alarm, such as wechat and email notification
            FMT. Println ("err error message:", ERR)
    //If there is no exception capture, the error panic will be reported directly, and an error will occur at runtime
    num1 := 10
    num2 := 0
    res := num1 / num2
    FMT. Println ("res result:", RES)
func main() {
    FMT. Println ("if the program doesn't quit, go to me")

Print results

Err error message: runtime error: integer divide by zero
If the program doesn't quit, go to me

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Recommended Today

Hive built-in function summary

1. Related help operation functions View built-in functions: Show functions; Display function details: desc function ABS; Display function extension information: desc function extended concat; 2. Learn the ultimate mental method of built-in function Step 1: carefully read all the functions of the show functions command to establish an overall understanding and impression Step 2: use […]