Skip to content

Latest commit

 

History

History
93 lines (63 loc) · 2.13 KB

File metadata and controls

93 lines (63 loc) · 2.13 KB

41) Errors

Linkedin Follow X Follow
Interactive Learning


Errors

Many languages use exceptions and try/catch blocks to handle errors.

Go does not. In Go, errors are just values.

The error Type

Go has a built-in type called error.

A function that can fail returns an error as its last return value.

If nothing went wrong, the error is nil.

Creating Errors

There are two common ways to create an error:

↳ 1) errors.New

import "errors"

err := errors.New("something went wrong")

This creates a simple error with a message.

↳ 2) fmt.Errorf

import "fmt"

name := "config.yaml"
err := fmt.Errorf("file not found: %s", name)

This creates an error with formatted text, just like fmt.Sprintf.

Example Code

There are some error declarations in main.go file.

But they are incomplete.

Fix the Code

Open main.go file and complete the code lines.

Then validate your code by running:

go run topic.go 41 validate

✅ If everything is ok, you should see:

OK!

Conclusion

Now you know what errors are in Go.

Continue to the next topic 👇

Error Handling ⮕️