Ad space (banner)
๐ŸนGo Lessons
Lesson 10 / 68

Error Handling

In this lesson you will learn the basics of error handling in Go and how to write programs that allow for unexpected failure. This is for anyone searching for "Go error handling how to use".

Go has no exception mechanism; the standard practice is to return an error as one of a function's return values. It works like insurance: you decide in advance what to do if something goes wrong.

The sample code has divide() return two values, (float64, error), creating and returning an error with errors.New() when asked to divide by zero. The caller then checks for failure with if err != nil.

A common stumbling block for beginners is carrying on without checking err. Forgetting that check is how bugs slip through, so make it a habit. You will see if err != nil constantly in Go, and that repetition is the point: it is a deliberate, safety-first design that refuses to let an error pass unnoticed.

In real-world development this error-value style is used for nearly everything that can fail, from file operations to network calls.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)