Go 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 }
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) }
How to customize error:
// errorString is a trivial implementation of error. type errorString struct { s string } func (e *errorString) Error() string { return e.s }
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!