Julia Error Design
Error design is the choice of how a function reports a failure. The choice is throw or return.
Throw for input the function cannot use
A negative age is not usable. The function throws, and catch prints a fixed message.
function check_age(age)
if age < 0
throw(ArgumentError("negative"))
end
age
end
try
check_age(-1)
println("No error")
catch
println("Invalid age")
endReturn a value for an expected miss
A search that finds nothing is a normal outcome. The function returns 0 for a miss.
function find_index(values, target)
for i in eachindex(values)
if values[i] == target
return i
end
end
0
end
println(find_index([10, 20, 30], 20))
println(find_index([10, 20, 30], 99))The caller treats each report differently
A good score returns as a plain value. A bad score throws and catch prints a fixed message.
function score_or_zero(score)
if score < 0
throw(ArgumentError("negative"))
end
score
end
try
println(score_or_zero(85))
catch
println("Bad score")
end
try
println(score_or_zero(-1))
catch
println("Bad score")
endExample
function valid_age(age)
if age < 0
throw(ArgumentError("negative"))
end
age
end
function find_index(values, target)
for i in eachindex(values)
if values[i] == target
return i
end
end
0
end
try
println(valid_age(30))
catch
println("Bad age")
end
println(find_index(["Ada", "Bo"], "Bo"))
println(find_index(["Ada", "Bo"], "Cy"))Key points
- Throw: Throwing signals a failure the caller must handle before using a result.
- Return: Returning a value reports an expected outcome without stopping the program.
- Decision: For each failure, decide throw or return before writing the function.
- Invalid input: Throw for input the function cannot use at all.
- Expected miss: Return a plain value when a search simply finds nothing.
In this example, valid_age returns 30 for a good age, and find_index returns 2 for a found name and 0 for a name that is not found. Throwing handles the unusable case, and returning handles the expected miss.
Note
A thrown error stops the current path, while a returned value lets the caller check it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
A function gets an age of -5, which it cannot use at all. What should it do?