Lesson Overview

Welcome to this thrilling session on runtime errors in Go programming. We're going to delve into runtime errors, understand their types and occurrences, and learn how to handle them. Mastering this will make your Go code reliable and fail-safe.

Today, we'll dissect runtime errors, categorize them, and learn how to identify and prevent them in Go programs.

Understanding Runtime Errors

Runtime errors appear during your program's execution and prevent the program from running as expected. Such errors occur when commands, even though syntactically correct, are logically impossible to execute.

Consider the array in Go below, which consists of five members. We're trying to access the non-existent sixth member:

package main

import "fmt"

func main() {
    array := [5]int{1, 2, 3, 4, 5}

    fmt.Println(array[5])  // Error: invalid argument: index 5 out of bounds [0:5]
}

The error returned: invalid argument: index 5 out of bounds [0:5], indicates we're trying to access an element outside the declared limit.

Types of Runtime Errors in Go

Runtime errors occur in various forms, including:

  1. Nil pointer dereferences: Attempting to access a nil object’s property.
  2. Index out of range: Accessing an array beyond its limits.
  3. Division by zero: Attempting to divide a number by zero.

Go uses a built-in panic mechanism to deal with such errors. Below are examples of the errors mentioned:

package main

import "fmt"

func main() {
    var pointer *string
    fmt.Println(*pointer)  // Nil pointer dereference error.
}
func main() {
    array := []int{1, 2, 3}

    fmt.Println(array[3])  // Index out of bound error.
}
func main() {
    number := 1
    zero := 0

    fmt.Println(number / zero)  // Division by zero error.
}
Identifying Runtime Errors

Go generates specific messages for runtime errors, such as panic: runtime error: integer divide by zero for a division by zero error.

package main

import "fmt"

func main() {
    number := 10
    zero := 0
    fmt.Println(number / zero)  // Division by zero error.
}

When this code runs, Go throws a division-by-zero error.

Fixing Runtime Errors
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