Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 40 ยท Errors and I/O

Errors and Exceptions

Handle failure in Julia: read common error messages, use throw, error and @assert, catch exceptions with try/catch/finally, define custom exception types.

Programs fail: a file is missing, a string is not a number, an index is out of range. Julia reports such problems by throwing an exception, which stops the normal flow of the program and unwinds the call stack until some code catches the exception, or until it reaches the top and the program prints an error and exits. Good error handling means three things: understanding what the messages say, throwing useful errors from your own code, and catching only the failures you can actually deal with.

In this lesson you will learn to read the common error types and stack traces, to use throw, error and @assert, to write try/catch/finally, and to define your own exception types. Julia code is read-only on this site, with the printed errors shown as comments; Python stand-ins use the same control flow (Python's try/except/finally is a close cousin) so you can run and change working examples.

Reading error messages

When code fails at the REPL, Julia prints the exception type, a message, and a stack trace: the chain of function calls that led to the failure, innermost first.

JULIA
julia> v = [10, 20, 30];

julia> v[5]
ERROR: BoundsError: attempt to access 3-element Vector{Int64} at index [5]
Stacktrace:
 [1] getindex(A::Vector{Int64}, i::Int64)
   @ Base ./essentials.jl:...
 [2] top-level scope
   @ REPL[2]:1

Read it from the top: the first line says what went wrong, and the trace tells you where. Frames in your own files, shown with the file name and line number, are usually the interesting ones, while frames from Base just show how the failure travelled. Here are the exceptions you will meet most often:

Exception Typical cause
BoundsError Index outside an array, for example v[5] on three elements
KeyError Missing dictionary key: KeyError: key "x" not found
MethodError No method matches the argument types: no method matching +(::String, ::Int64)
ArgumentError A function got an invalid value, such as parse(Int, "abc")
DomainError A math function was given a value outside its domain
DivideError Integer division by zero, as in div(1, 0)
UndefVarError A variable is not defined in scope
TypeError A value had the wrong type for an annotation or assertion
InexactError A conversion would lose information: Int(2.5)
StackOverflowError Runaway recursion

MethodError deserves special mention because it is the most common error in Julia. It tells you that no method of the function accepts those argument types, and it lists the closest candidates, which usually reveals a missing conversion or a wrong argument order.

Anatomy of a failure

throw Something goes wrong.
Unwind Calls are abandoned, innermost first.
catch A handler takes over.
finally Cleanup always runs.
1 / 2

Throwing errors

You create failures with throw and error:

JULIA
function withdraw(balance, amount)
    amount > 0 || throw(ArgumentError("amount must be positive, got $amount"))
    amount <= balance || error("insufficient funds: balance $balance, requested $amount")
    return balance - amount
end

withdraw(100, 30)      # 70
withdraw(100, -5)      # ERROR: ArgumentError: amount must be positive, got -5
withdraw(100, 500)     # ERROR: insufficient funds: balance 100, requested 500
  • throw(exception) throws any exception object. Pick a built-in type that describes the problem (ArgumentError, DomainError, BoundsError, KeyError...), so callers can catch exactly it.
  • error("message") is a shorthand that throws an ErrorException with a string. It is fine for quick scripts and for failures that should never be handled.
  • The idiom condition || throw(...) is a compact guard that reads as "this must hold, or else...".
  • @assert condition "message" checks something that must always be true if your code is correct, and throws AssertionError. Assertions document assumptions; do not use them to validate user input, because a failed assertion means a bug in your code, not bad input. Use ArgumentError for bad input.

Prefer to avoid exceptions for ordinary control flow. Exceptions in Julia are slower than normal returns, and a failure that happens often should be part of the function's result. Standard functions offer both: parse(Int, s) throws, whereas tryparse(Int, s) returns nothing on failure. Similarly get(dict, key, default) instead of catching KeyError.

try, catch and finally

try/catch runs a block and, if an exception is thrown inside, jumps to the catch block:

JULIA
function safe_parse(s)
    try
        return parse(Int, s)
    catch err
        println("could not parse ", repr(s), ": ", err)
        return missing
    end
end

safe_parse("42")      # 42
safe_parse("4x2")     # prints a "could not parse" line mentioning the invalid digit
                      # returns missing

Be careful with layout: catch err binds the exception to a variable only when err is on the same line as catch. If you write catch followed by a newline and then a statement err, that line is just code that is run. To ignore the exception, write catch alone on its line.

Catching everything is rarely right, because you will also hide bugs. Test the type and re-throw what you do not handle:

JULIA
try
    risky()
catch err
    if err isa KeyError
        println("missing key: ", err.key)
    else
        rethrow()          # keeps the original stack trace
    end
end

The finally block runs whatever happens, with or without a catch: after success, after an exception, and even when the try block returns. Use it for cleanup such as closing a file or releasing a lock.

JULIA
io = open("data.txt", "w")
try
    write(io, "hello")
    error("disk on fire")       # something fails midway
catch err
    println("caught: ", err)
finally
    close(io)                   # runs in every case
end

Since Julia 1.8 there is also an optional else clause, which runs only if no exception occurred, placed between catch and finally. And a try block is an expression: x = try parse(Int, s) catch; 0 end gives a value. In file-handling code, though, the open(...) do io ... end form closes the file for you, which is usually neater (see Files and I/O).

The same flow in Python

Python's try/except/else/finally has the same four parts. This stand-in raises and handles exceptions with the same shapes as the Julia withdraw example, and prints the order in which each block runs.

Python try, catch, else and finally

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The RuntimeError slips past the inner handler, because only ValueError is caught there, runs its finally on the way out, and is finally caught by the outer one. Julia behaves the same way when you test the type and rethrow() the rest.

Custom exception types

To let callers react to your own failure modes, define a type that is a subtype of Exception:

JULIA
struct InsufficientFunds <: Exception
    balance::Float64
    requested::Float64
end

function Base.showerror(io::IO, e::InsufficientFunds)
    print(io, "InsufficientFunds: balance ", e.balance,
              " is less than the requested ", e.requested)
end

function withdraw(balance, amount)
    amount <= balance || throw(InsufficientFunds(balance, amount))
    return balance - amount
end

try
    withdraw(100.0, 250.0)
catch err
    if err isa InsufficientFunds
        shortfall = err.requested - err.balance
        println("Please deposit ", shortfall, " first.")   # Please deposit 150.0 first.
    else
        rethrow()
    end
end

The fields carry data that a handler can use without parsing a message string, and the showerror method controls how the error prints when nobody catches it. Name exception types after the problem (InsufficientFunds, ConfigError), not the place it came from. A package often defines one abstract parent, such as abstract type MyPackageError <: Exception end, so users can catch all of its errors at once with a single isa check.

This stand-in does the same in Python: a custom class carrying data, and a handler that uses the fields rather than the message text.

Python A custom exception with data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Stack traces and logging

When you catch an exception you can still get the trace of where it happened:

JULIA
try
    risky()
catch err
    bt = catch_backtrace()
    showerror(stdout, err, bt)       # prints the message and the trace
    println()
end

In real programs, prefer the logging macros to scattered println calls: @info, @warn and @error print leveled, timestamp-capable messages and accept key-value pairs, as in @error "failed to load" file exception=(err, catch_backtrace()). This logs the message and the full trace without stopping the program.

A few practical rules finish the picture:

  • Fail early with a clear message at the boundary where bad data enters, and keep the inner code simple.
  • Catch the narrowest type you can handle, and rethrow() the rest.
  • Do not use an empty catch to silence problems; at least log the error.
  • Keep try blocks small. A huge block makes it unclear which statement failed.
  • For tasks and threads, errors are stored inside the task and appear when you fetch or wait it, wrapped in a TaskFailedException; see Threads, Tasks and Distributed Computing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which exception is raised by [1, 2, 3][7]?

    An index outside the valid range of an array throws BoundsError. KeyError is for dictionaries.
  2. 2. What does the finally block do?

    finally always runs when leaving the try statement, whether normally, by an exception or by return.
  3. 3. In a handler that cannot deal with the exception it caught, what should you call to pass it on with its stack trace intact?

    rethrow() re-raises the current exception with the original backtrace. error(err) would create a new, less informative exception.
  4. 4. Why is tryparse(Int, s) often better than try parse(Int, s) catch ... end for user input that may be wrong?

    When failure is a normal outcome, a return value is clearer and cheaper than an exception.
  5. 5. What must a custom error type be a subtype of?

    Subtype Exception so throw and catch treat the value as an exception. Add fields for the data a handler needs.

Summary

  • Exceptions unwind the call stack until a catch handles them; the message names the type, and the stack trace shows where.
  • Know the common types: BoundsError, KeyError, MethodError, ArgumentError, DomainError, UndefVarError.
  • Use throw(SomeException(...)), error("msg") and @assert to signal problems; prefer tryparse-style functions when failure is routine.
  • try/catch err/finally handles errors and guarantees cleanup; test the type with isa and rethrow() what you cannot handle.
  • Define custom exceptions as struct ... <: Exception with fields, and customize their display with Base.showerror.

Next, read and write data in Files and I/O.