In julia we like to distinguish different things using different types (exceptions are one such thing).
In most languages they also like to distinguish different exceptions with different types.
In particular in julia
try
foo()
catch err
if err isa BarError
# Handle it
elseif err isa BlargError
# Handle that
else
rethrow()
end
end
Saying error("it is borked because the Blarg is flumoxed")
causes an ErrorException
to be thrown.
This is an incredibly unhelpful error, typewise.
You can;t work out what threw it or why.
So you canāt handle it safely.
error
exists for when you canāt be bothered declaring an exception type.
Or working out which existing one to use.
It belongs in user-scripts, and quick prototypes.
It doesnāt belong in registered packages, and it particularly doesnāt belong in Standard Libraries / Base
Most gone now. However, the run
command still throws one (https://github.com/JuliaLang/julia/pull/27900).
I suggest that ErrorException
should be treated as if it were an uncatchable exception type.
I suspect our over reliance on using error
might come back to prior experiences we have using other languages where declaring your own exception type is difficult.
But in julia it is easy
struct MyError <:Exception end
or
struct MyErrorWithMsg <:Exception
msg::String
end
There is also @assert
for things that a programmer errors.
So you can replace
if val == true
# do it
elseif val==false
# do not do it
else
error("This should never happen")
end
With
if val == true
# do it
elseif val==false
# do not do it
else
@assert(false, "This should never happen")
end
Which is clearer.
I am not saying I am perfect, I have packages where I was lazy and used error
,
rather than using the right exception type.
But lets try and clean those out now, while we are getting ready for 1.0.
Save error
for end-users; keep it out of your packages