Golang error throwing method

Release: 2020-01-14 16:13:53
Original
4006 people have browsed it

Golang error throwing methodGo language does not provide try...catch exception handling methods like those in Java and C# languages, but instead throws them up layer by layer through function return values.

The error handling function provided by the Go standard package:

error is an interface:

type error interface {
    Error() string
}
Copy after login

How to create error:

// example 1
func Sqrt(f float64) (float64, error) {
    if f < 0 {
        return 0, errors.New("math: square root of negative number")
    }
    // implementation
}

// example 2
if f < 0 {
    return 0, fmt.Errorf("math: square root of negative number %g", f)
}
Copy after login

How to customize error:

// errorString is a trivial implementation of error.
type errorString struct {
    s string
}

func (e *errorString) Error() string {
    return e.s
}
Copy after login

There are generally three error handling strategies in the go language:

1. Return and check error values: success and different errors are represented by specific values, and the upper-layer code checks the error value to determine what is being called. The execution status of func

2. Custom error type: specific errors are represented by custom error types, and the upper-level code determines the error type through type assertions

3. Hiding internal details Error handling: Assume that the upper-layer code does not know any details of the error returned by the called function, and directly returns the error

The output of the Error method of the interface is for people to see, not for the machine. We usually print the string returned by the Error method to the log or display it on the console. Never determine how to handle an error by determining whether the string returned by the Error method contains a specific string.

For more golang knowledge, please pay attention to the golang tutorial column.

The above is the detailed content of Golang error throwing method. 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