1. Go native Error
The error native to Go is an interface type, and any implementation of the error () method is an error.
type error interface {
Error() string
}
Copy the code
Normally we use errors.new () to generate an error. Note that each error returned by this method is different, even though the string representing the error is exactly the same, because this method returns an object pointer to error
// New returns an error that formats as the given text.
// Each call to New returns a distinct error value even if the text is identical.
func New(text string) error {
return &errorString{text}[Ref 1](#Ref) [Ref 1](#Ref)
}
// errorString is a trivial implementation of error.
type errorString struct {
s string
}
func (e *errorString) Error(a) string {
return e.s
}
Copy the code
2. The Error and the Exception
Go does not have exceptions, but instead supports multiparameter returns containing errors. With multiple parameters and simple conventions, Go lets programmers know when something is wrong and feedback true exceptions by leaving Panic in place.
Defer and recovery ()
Ref
- Go structure and initialization
- Go language data type
- The implementation principles of Golang Panic and Recover