Tutorial by Examples

The simplest way to create an error is by using the errors package. errors.New("this is an error") If you want to add additional information to an error, the fmt package also provides a useful error creation method: var f float64 fmt.Errorf("error with some additional informatio...
In Go, an error is represented by any value that can describe itself as string. Any type that implement the built-in error interface is an error. // The error interface is represented by a single // Error() method, that returns a string representation of the error type error interface { Erro...
In Go you don't raise an error. Instead, you return an error in case of failure. // This method can fail func DoSomething() error { // functionThatReportsOK is a side-effecting function that reports its // state as a boolean. NOTE: this is not a good practice, so this example // tur...
In Go errors can be returned from a function call. The convention is that if a method can fail, the last returned argument is an error. func DoAndReturnSomething() (string, error) { if os.Getenv("ERROR") == "1" { return "", errors.New("The method fai...
A common mistake is to declare a slice and start requesting indexes from it without initializing it, which leads to an "index out of range" panic. The following code explains how to recover from the panic without exiting the program, which is the normal behavior for a panic. In most situat...

Page 1 of 1