Julia Custom Exceptions
Custom exceptions are error types a programmer defines. A custom exception names one failure in a program in plain terms.
A custom exception is a small struct
This struct names one failure. Throwing it inside try lets catch print a fixed message.
struct AgeError <: Exception end
try
throw(AgeError())
catch
println("Age is not allowed")
endA custom exception can carry a value
This exception carries a score. The catch block still prints only a fixed message.
struct ScoreError <: Exception
value::Int
end
try
throw(ScoreError(120))
catch
println("Score is out of range")
endA function can throw a custom exception
The check throws when the age is negative. The caller catches it and prints a fixed message.
struct AgeError <: Exception end
function check_age(age)
if age < 0
throw(AgeError())
end
age
end
try
check_age(-3)
catch
println("Age is not allowed")
endExample
struct LowScore <: Exception end
struct HighScore <: Exception end
function check_score(score)
if score < 0
throw(LowScore())
end
if score > 100
throw(HighScore())
end
score
end
try
check_score(-5)
catch
println("Score is too low")
end
try
check_score(120)
catch
println("Score is too high")
endKey points
- Custom exception: A struct that is a subtype of Exception defines a new error type.
- Throw: Throwing a custom exception signals that its failure has happened.
- Catch: A catch block runs when the thrown exception reaches it.
- Fixed message: A catch block can print a fixed message instead of the error value.
- Field: A custom exception struct can hold a value in a field.
In this example, check_score throws LowScore for a negative score and HighScore for a score above 100. Each catch block prints a fixed message for its failure.
Note
A custom exception keeps error handling in the program's own terms.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What defines a new custom exception type in Julia?