David in Canada

 

Tech, life, and everything in between.

Day 11 — Error Handling in Go

Updated at # Tech # Go

Overview

Today I learned how Go handles errors explicitly through the error type.

Unlike languages that rely on exceptions, Go treats errors as ordinary values. This makes control flow more visible and forces programmers to handle failures directly.


What I Built

A Safe Calculator CLI that:


Key Concepts

Errors Are Values

In Go, functions often return:

value, err := someFunction()

Then the caller checks:

if err != nil {
    // handle error
}

This is the standard Go pattern.


Custom Error Type

type MyError struct {
    Message string
}

func (e MyError) Error() string {
    return e.Message
}

By implementing Error() string, a type satisfies the built-in error interface.


Safe Division

func safeDivide(a, b int) (int, error)

Returns an error when attempting to divide by zero.


Safe Square Root

func safeSqrt(x float64) (float64, error)

Returns an error when attempting to calculate the square root of a negative number.


Input Validation

Used fmt.Scan together with error checking to validate user input before performing calculations.


Example Output

Enter two integers: 10 0
Error: cannot divide by zero

Enter a number to find its square root: -4
Error: cannot take square root of a negative number

Key Takeaways


Reflection

This lesson made Go feel much closer to production code.

Error handling changes the way programs are written: instead of assuming success, the code must always consider what can go wrong. That mindset is essential for backend engineering.


Next Steps