Error Handling

Many operations can fail:

  • Opening a file

  • Reading user input

  • Parsing JSON

  • Network communication

  • Database access

Go treats errors as ordinary values rather than exceptions.

Instead of:

try {
    ...
}
catch (...) {
    ...
}

Go uses:

result, err := SomeFunction()
 
if err != nil {
    // Handle the error
}

This makes the possibility of failure explicit.


Multiple Return Values

Functions may return multiple values.

Example:

func Divide(a, b int) (int, error) {
    if b == 0 {
        return 0, fmt.Errorf("division by zero")
    }
 
    return a / b, nil
}

Return values:

  • Result

  • Error


Calling a Function

result, err := Divide(10, 2)
 
if err != nil {
    fmt.Println(err)
    return
}
 
fmt.Println(result)

Output:

5

Error Case

result, err := Divide(10, 0)
 
if err != nil {
    fmt.Println(err)
    return
}

Output:

division by zero

The error Type

The second return value usually has type:

error

No error:

err == nil

Error occurred:

err != nil

nil represents the absence of a value.


Creating Errors

The standard way:

return 0, fmt.Errorf("division by zero")

fmt.Errorf() creates an object implementing the error interface.


The Famous Go Pattern

Real Go programs frequently contain:

result, err := SomeFunction()
 
if err != nil {
    return err
}

This is one of the most recognizable idioms in Go.


The Blank Identifier

Sometimes one return value is not needed.

Ignore the error:

result, _ := Divide(10, 2)

Ignore the result:

_, err := Divide(10, 0)

The underscore (_) tells Go to discard the value.


:= vs =

One of the most common beginner mistakes.

Short Variable Declaration

x, err := Divide(10, 2)

Creates new variables.

Equivalent to:

var x int
var err error
 
x, err = Divide(10, 2)

Use := only when at least one non-blank variable is new.


Assignment

Once variables already exist:

_, err = Divide(10, 0)

Use the normal assignment operator.


Why This Fails

_, err := Divide(10, 0)

Compiler:

no new variables on left side of :=

Reason:

  • _ is not a variable.

  • err already exists.

Therefore no new variables are being declared.


This Works

x, err := Divide(10, 2)
 
y, err := Divide(20, 5)

Because:

  • y is a new variable.

  • err already exists.

Go only requires one newly declared variable.


Mental Model

Think of the operators as:

:=   Declare at least one new variable
 
=    Assign to existing variables

Whenever writing :=, ask:

“Am I creating a new variable?”

If the answer is “No”, use =.


Common Error Handling Pattern

value, err := ReadFile()
 
if err != nil {
    return err
}
 
fmt.Println(value)

Handle errors immediately after the function call.


Common Beginner Mistakes

Forgetting to Check Errors

Incorrect:

result, err := Divide(10, 0)
 
fmt.Println(result)

Correct:

if err != nil {
    fmt.Println(err)
    return
}

Using := Instead of =

Incorrect:

_, err := Divide(20, 0)

Correct:

_, err = Divide(20, 0)

Ignoring Returned Errors

Even if a program appears to work, ignoring errors can hide bugs.

Always decide explicitly whether to:

  • Handle the error

  • Return the error

  • Ignore it using _


Comparison with C++

GoC++
(value, error)Exceptions or error codes
if err != niltry/catch
nilnullptr (conceptually)
fmt.Errorf()throw std::runtime_error(...) (roughly comparable)
:=Variable declaration
=Assignment

Session Summary

Topics covered:

  • Multiple return values

  • The error type

  • nil

  • Creating errors

  • Explicit error checking

  • Blank identifier (_)

  • Difference between := and =

Practical skills gained:

  • Writing functions that return errors

  • Handling failures explicitly

  • Understanding Go’s error handling philosophy

  • Knowing when to declare variables and when to assign them


Key Takeaways

  • Errors are ordinary values in Go.

  • Functions commonly return (value, error).

  • Always check err immediately after a function call.

  • nil means “no error”.

  • := declares variables.

  • = updates existing variables.

  • At least one non-blank variable must be new when using :=.


Next Topics