Hello!
When using exceptions and try-catch blocks, it’s very common to handle some specific types of exceptions, and propagate everything else. Here’s how this is usually done:
try
# body with potential exceptions
catch e
if e isa AssertionError
# handle assertion errors here
elseif e isa InexactError
# handle conversion errors here
else
rethrow() # everything else is passed on
end
end
For me (and possibly others with some background in functional programming, like myself), this seems a bit cumbersome. There must be a way to be able to write this in a nicer, more concise format, without if
s. I can, for example, introduce a helper function using type dispatch:
handle_error(e::AssertionError) = nothing # handle assertion errors here
handle_error(::InexactError) = nothing # handle conversion errors here
handle_error(_) = rethrow()
try
# body with potential exceptions
catch e
handle_error(e)
end
No more ifs, but now the handling code is somewhat separated from the location of the error. If I follow this thought, the following notation comes to my mind:
try
# body with potential exceptions
catch e::AssertionError
# handle assertion errors here
catch ::InexactError # note the missing variable
# handle conversion errors here
end
# every other error is propagated (uncaught) implicitly
This could be pure syntactic sugar, of course, resolving to either of the two forms above. But it would make the code so much clearer, IMHO!
I tried to find a conversation on this topic, but I couldn’t find any (except for this ancient one), which took me by surprise.
So, WDYT?