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
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
tryruns the protected code.catch errruns only if an exception was thrown;errholds the exception object.finallyalways 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:
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))
end2.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:
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
endok: 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:
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)
end60.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:
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 returningnothing. 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.
function mean_of(v)
@assert !isempty(v) "mean of an empty collection"
return sum(v) / length(v)
endTest yourself
When does a finally block run?
- Only if an error occurs
- Only if no error occurs
- Always, after try (and catch) finish
- Never, it's deprecated
What does error("oops") throw?
- ArgumentError
- ErrorException
- Exception
- nothing
How do you create your own exception type?
- struct MyError <: Exception ... end
- class MyError(Exception)
- exception MyError end
- abstract type MyError end