美文网首页
Go - error

Go - error

作者: 隐号骑士 | 来源:发表于2024-12-24 23:08 被阅读0次

By convention, errors have type error, a simple built-in interface.

type error interface {
    Error() string
}

Usage

Basically as a part return from function

package main

import (
    "errors"
    "fmt"
)

func divide(a, b int) (int, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}

func main() {
    result, err := divide(10, 0)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println("Result:", result)
}

Error vs. Panic

  • Error: Recoverable
  • Panic: Not Recoverable, exit and triggers defer , can be caught by recover

An example of panic

package main

import "fmt"

func main() {
    defer fmt.Println("First defer")
    defer fmt.Println("Second defer")

    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered:", r)
        }
    }()

    panic("Something bad happened")
    fmt.Println("This line will not be executed")
}

相关文章

  • 2021/05/04关于GO的错误处理(error)

    1.首先何谓error GO中的error就是一个普通的接口(实现了Error方法) 位于源码builtin.go...

  • 第05天(异常、文本文件处理)_01

    01_error接口的使用.go 02_error接口应用.go 03_显式调用panic函数.go 04_数组越...

  • 《Go源码解读篇》之 Error

    Go 语言中必不可少的类型 --- error,Go 中的原生代码少,而且易掌握. What is error? ...

  • go error处理

    背景介绍 如果你有写过Go代码,那么你可以会遇到Go中内建类型error。Go语言使用error值来显示异常状态。...

  • 报错:go run: cannot run *_test.go

    ERROR:go run: cannot run *_test.go files 比如执行:go run aaa_...

  • Go 基础 3:error handling

    官网: https://blog.golang.org/error-handling-and-go error对于...

  • Golang实践-error

    Golang实践-error Error Go error 是一个普通的接口,普通的值 经常使用errors.Ne...

  • 基础-3

    异常处理 error接口:Go中的一个关于错误处理的标准模式,属于Go内建的接口类型;type error int...

  • Go error

    error Go 使用 error 类型来表示函数执行过程中遇到的错误,如果返回的 error 值为 nil,则表...

  • go error

    1.why shoud we wrap go error 2.usage 3.details errors.Is ...

网友评论

      本文标题:Go - error

      本文链接:https://www.haomeiwen.com/subject/xlkeejtx.html