Best way to write nested try/catch blocks

I have a piece of code that tries a few things in a nested try/catch block which can look ugly. Is there a better way to write this? Using Macros perhaps? I can imagine wrting a macro with this syntax instead

`@nested_trycatch zero(T) T(0) rand(T) Vector{T}(undef, 1)[1] throw(“the type $T is not supported”)

some_elm(::Type{T}) where T = begin
    try
        return zero(T)
    catch
        try
            return T(0)
        catch
            try
                rand(T)
            catch
                try
                    Vector{T}(undef, 1)[1]
                catch
                    throw("the type $T is not supported")
                end
            end
        end
    end
end

Organize your code differently. Traits would help in general, but may require more investment, hasmethod would be the quick & dirty way.

FWIW, if this is related to

then just use one of the solutions suggested there; if you are OK with random values then it makes little sense to attempt to get a zero first — pretty much the same types have rand and zero defined.

A simple way would be just to flatten it:

some_elm(::Type{T}) where T = begin
    try
        return zero(T)
    catch end

    try
        return T(0)
    catch end

     try
         return rand(T)
     catch end

     try
         return Vector{T}(undef, 1)[1]
     catch end

     throw("the type $T is not supported")
end

Which I would feel is clean enough…especially if you include comments for each attempt that separate the different tries…

1 Like