Overview

Welcome, aspiring programmer! Today, we're learning about error handling in Go. This subject is critical for addressing potential issues in your programs. Through practical examples, we'll see how Go's approach to error management contributes to the design of resilient and robust software.

Errors are inevitable in any program. However, by properly handling errors in Go, we can create solid applications that perform reliably even when things don't go as planned.

Understanding the Need for Error Handling

Life often throws us curve balls, and the same is true in the world of programming. Unexpected situations can arise — such as a user providing the wrong type of input or a required file being unlocatable. Anticipating and dealing with these scenarios is what error handling is all about.

Working with Error Handling in Go

Unlike other languages, Go doesn't implement traditional try/catch blocks. Instead, Go encourages explicit error checking by treating errors as ordinary variables that can be declared and manipulated.

Below is an example of how we might handle an error in Go:

if err != nil {
    // Handle the error
}

Consider a scenario where you attempt to open a non-existent file. We open the file with os.Open. To use it, you need to import "os".

package main

import (
    "fmt"
    "os"   
)

func main() {
    file, err := os.Open("non_existent_file.txt")
    if err != nil {
        fmt.Println("Oops! This file is not present")
        fmt.Println("Here is the error description:", err)
    } else {
        fmt.Println(file.Name())  // Code for the case file does exist
    }
    
    // Output:
    // Oops! This file is not present
    // Here is the error description: open non_existent_file.txt: no such file or directory
}

In this case, Go essentially says, "Okay, I'll TRY to open this file. Uh oh, it doesn't exist." In response, it generates an error that you can handle proactively.

Implementing Error Handling in Go

Let's write two Go scripts to demonstrate error handling. Each script will provide unique messages for successful and unsuccessful executions.

First, let's look at a block of code running without errors:

_, err := fmt.Println("Everything is fine!")
if err != nil {
    fmt.Println("Something wrong happened:", err)
} else {
    fmt.Println("We will see this if there is no error!")
}

Secondly, we simulate a scenario that generates an error:

package main

import (
    "fmt"
    "strconv"   
)

func main() {
    _, err := strconv.ParseInt("3a", 10, 64)
    if err != nil {
        fmt.Println("Oops! You can't convert this string to an integer.")
    }
    fmt.Println("This code will execute")
}

Note that the code can keep being executed if the error is handled.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal