TExcelTAD
Home › Julia › Julia Error Handling

Julia Error Handling

When something goes wrong — a missing key, a bad argument, an impossible conversion — Julia throws an exception. If nothing catches it, the program stops with an error message. With try/catch you can handle the problem and keep going.

try, catch, finally

julia · try it yourself
function safe_divide(a, b)
    try
        return div(a, b)
    catch err
        println("caught a ", typeof(err))
        return nothing
    finally
        println("division attempted: $a ÷ $b")
    end
end

println(safe_divide(10, 3))
println(safe_divide(10, 0))
division attempted: 10 ÷ 3
3
caught a DivideError
division attempted: 10 ÷ 0
nothing
  • try runs the protected code.
  • catch err runs only if an exception was thrown; err holds the exception object.
  • finally always runs, error or not — ideal for cleanup such as closing files.

Built-in exception types

Exception Typical cause
ArgumentError an argument has an invalid value
BoundsError index outside an array
KeyError missing dictionary key
DomainError maths outside the valid domain (sqrt(-1))
DivideError integer division by zero
InexactError conversion would lose information
MethodError no method matches the argument types
UndefVarError using a name that isn't defined
ErrorException thrown by error("message")

Reacting to the type of error

catch catches everything, so check the type with isa to handle only what you expect and rethrow the rest:

julia · try it yourself
function lookup(prices, item)
    try
        return prices[item]
    catch e
        if e isa KeyError
            return "no price for $(e.key)"
        else
            rethrow()
        end
    end
end

prices = Dict("tea" => 2.5)
println(lookup(prices, "tea"))
println(lookup(prices, "cake"))
try
    lookup([1, 2], 5)        # a BoundsError is rethrown
catch e
    println("outer handler: ", typeof(e))
end
2.5
no price for cake
outer handler: BoundsError

Throwing errors

Use throw with an exception object, or the shortcut error("message"), which throws an ErrorException:

julia · try it yourself
function set_age(age)
    age isa Integer || throw(ArgumentError("age must be an integer"))
    age >= 0 || throw(DomainError(age, "age cannot be negative"))
    age > 150 && error("unrealistic age: $age")
    return age
end

for a in (30, 2.5, -4, 200)
    try
        println("ok: ", set_age(a))
    catch e
        println(sprint(showerror, e))
    end
end
ok: 30
ArgumentError: age must be an integer
DomainError with -4:
age cannot be negative
unrealistic age: 200

sprint(showerror, e) turns an exception into the same message Julia would print, without the stack trace.

Custom exception types

Define a struct that subtypes Exception. Add a showerror method for a friendly message:

julia · try it yourself
struct InsufficientFunds <: Exception
    balance::Float64
    requested::Float64
end

Base.showerror(io::IO, e::InsufficientFunds) =
    print(io, "InsufficientFunds: requested ", e.requested, " but balance is ", e.balance)

function withdraw(balance, amount)
    amount > balance && throw(InsufficientFunds(balance, amount))
    return balance - amount
end

println(withdraw(100.0, 40.0))
try
    withdraw(100.0, 250.0)
catch e
    println(sprint(showerror, e))
    println("short by ", e.requested - e.balance)
end
60.0
InsufficientFunds: requested 250.0 but balance is 100.0
short by 150.0

try is an expression

Like if, a try block returns a value, so it can give a fallback in one line. Julia 1.8+ also supports an else clause that runs only when no error occurred:

julia · try it yourself
input = ["42", "x7", "8"]
nums = [try parse(Int, s) catch; 0 end for s in input]
println(nums)

function checked_sqrt(x)
    r = 0.0
    try
        r = sqrt(x)
    catch
        println("failed for ", x)
    else
        println("succeeded with ", r)
    end
end
checked_sqrt(16)
checked_sqrt(-1)
[42, 0, 8]
succeeded with 4.0
failed for -1

Each clause of a try is its own scope, so r is created before the try; the assignment inside then updates it, and the else clause can read it.

Tip: Exceptions are relatively slow and make control flow harder to follow. For expected situations, prefer checks and values: get(dict, key, default), tryparse, checkbounds, or returning nothing. Reserve exceptions for truly exceptional cases.

Assertions

@assert cond "message" throws an AssertionError if the condition is false. Use it to document assumptions while developing; don't use it to validate user input.

julia
function mean_of(v)
    @assert !isempty(v) "mean of an empty collection"
    return sum(v) / length(v)
end

Test yourself

When does a finally block run?

  1. Only if an error occurs
  2. Only if no error occurs
  3. Always, after try (and catch) finish
  4. Never, it's deprecated

What does error("oops") throw?

  1. ArgumentError
  2. ErrorException
  3. Exception
  4. nothing

How do you create your own exception type?

  1. struct MyError <: Exception ... end
  2. class MyError(Exception)
  3. exception MyError end
  4. abstract type MyError end