Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid writing @try @catch @else #143

Closed
singularitti opened this issue Aug 17, 2022 · 2 comments · Fixed by #145
Closed

Avoid writing @try @catch @else #143

singularitti opened this issue Aug 17, 2022 · 2 comments · Fixed by #145
Assignees
Labels
enhancement New feature or request

Comments

@singularitti
Copy link
Member

singularitti commented Aug 17, 2022

Before v1.8, Julia does not support the try ... catch ... else syntax. So I have to use TryCatch.jl to do that:

function __run!(job::Job)
    # See https://github.com/JuliaLang/julia/issues/21130#issuecomment-288423284
    @try begin
        global result = job.def()
    @catch e
        job.stop_time = now()
        @error "come across `$e` when running!"
        job.status = e isa InterruptException ? INTERRUPTED : FAILED
        return e
    @else
        job.stop_time = now()
        job.status = SUCCEEDED
        return result
    @finally
        job.count += 1
    end
end

After moving the function definition to Thunk, I had the same problem (But since I was using Julia v1.8 to develop, so that was fine):

@try
    global result = thunk.f(thunk.args...; thunk.kwargs...)
@catch e
    setresult!(thunk, e)
    return e
@else
    setresult!(thunk, result)
    return result
end

But I just found out, I could just use finally and some tricks to avoid else (since try statement do not return what was included in finally):

try
    thunk.result = Some(thunk.f(thunk.args...; thunk.kwargs...))
catch e
    thunk.erred = true
    thunk.result = Some(e)
finally
    thunk.evaluated = true
end

If no error is raised, thunk.result will be returned; if erred, thunk.result will catch an error and still be returned. No matter what, thunk.evaluated is set to true.

@singularitti
Copy link
Member Author

So the topmost example could be rewritten as

function __run!(job::Job)
    try
        global result = job.def()
        job.stop_time = now()
        job.status = SUCCEEDED
    catch e
        job.stop_time = now()
        @error "come across `$e` when running!"
        job.status = e isa InterruptException ? INTERRUPTED : FAILED
    finally
        job.count += 1
    end
end

I probably did not use that because it was a three-part statement, where the last two could have erred, and I did not want them to be captured.

@singularitti
Copy link
Member Author

One good thing is that I do not have to define a global variable result to return! Since it is captured by thunk.result anyway.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
1 participant