Rethrow error from @async

hello,
I need help understanding why the rethrow from an @async does not work.
my test code is as follow:

bad_fun1() = error("this is error from bad_fun1")

function rethrow_fun1()
    try
        bad_fun1()
    catch e
        println("got error from bad_fun1, retrow to rethrow_fun1")
        rethrow(e)
    end
end

function main()
    try
        @async begin
            try
                rethrow_fun1() 
            catch
                println("got error from rethrow_fun1 at @async , rethrow to main")
                rethrow(e)
            end
        end
    catch e
        println("got error from rethrow_fun1, retrow to main")
        rethrow(e)
    end
end

try
    main()
catch e
    println("got error from main")
end

the output of this code is:

got error from bad_fun1, retrow to rethrow_fun1
got error from rethrow_fun1 at @async , rethrow to main

I expect to get the error all the way till the last try - catch but the rethrow from with in the @async does not seem to work…
Thanks in ahead for any help in the subject.

You should wait on the task you created, either by @sync or by explicit wait. For example

function main()
    @sync begin
        try
            @async begin
                try
                    rethrow_fun1()
                catch
                    println("got error from rethrow_fun1 at @async , rethrow to main")
                    rethrow(e)
                end
            end
        catch e
            println("got error from rethrow_fun1, retrow to main")
            rethrow(e)
        end
    end
end
julia> try
           main()
       catch e
           println("got error from main")
       end
got error from bad_fun1, retrow to rethrow_fun1
got error from rethrow_fun1 at @async , rethrow to main
got error from main
2 Likes

Thank you for the supper quick reply.
I’ll implement it in my code.
Can you elaborate alittle more about the logic for doing so?
It will help me avoid similar problams in the future.
Thank again.

@sync catches async thrown exceptions

@sync

  Wait until all lexically-enclosed uses of @async, @spawn, @spawnat and @distributed are complete. All exceptions thrown by enclosed async operations are collected and thrown as a CompositeException.