Day 5: Functions and Robust Error Handling in Go

Venkat Annangi
Venkat Annangi
23/09/2024 15:42 2 min read 46 views
#golang #108 days of golang

Day 5: Functions and Robust Error Handling in Go

In Go, functions are the building blocks of reusable code, while error handling ensures the robustness of your programs. Today, we’ll cover both in depth.

Step 1: Defining Functions

Functions in Go are defined using the func keyword. Here's a simple function:

func add(a int, b int) int {
    return a + b
}

This function takes two integers as arguments and returns their sum. You can call this function like so:

result := add(3, 4)
fmt.Println(result)  // Output: 7

Step 2: Multiple Return Values

Go functions can return multiple values, which is especially useful for error handling:

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, fmt.Errorf("cannot divide by zero")
    }
    return a / b, nil
}

You can call this function and handle errors like this:

result, err := divide(10, 0)
if err != nil {
    fmt.Println("Error:", err)
} else {
    fmt.Println("Result:", result)
}

Step 3: Defer, Panic, and Recover

Go provides defer, panic, and recover for advanced error handling. These are typically used for resource cleanup, handling unexpected errors, and recovering from panics:

func main() {
    defer fmt.Println("This will run last")
    fmt.Println("Hello")
    panic("Something went wrong")
}

Practical Exercise

Write a function to calculate the division of two numbers with error handling for division by zero. Add another function that uses defer to print a closing message after the calculation is complete.

Comments