Hasan Al-Baghdadi
Hasan Al-Baghdadi

Reputation: 452

Is it possible to return a value from a Julia function after throwing an error?

I want to be able to both throw both an error but still be able to get a value returned.

So what I've tried are the following two, but neither seem to behave the way I want them to:

function func()
    try
        error()
    catch e
        throw(e)
    finally
        return 10
    end
end

This returns a 10, but doesn't throw errors.

function func()
    try
        error()
    catch e
        throw(e)
    finally
        10
    end
end

This throws an error but doesn't return a 10.

Note: I get the same results as the second bit of code without using a finally

What I would want is to be able to call foo = func(), have the error get thrown and have foo = 10

Upvotes: 0

Views: 530

Answers (1)

Bill
Bill

Reputation: 6086

You probably do not want to do that. You likely want to return two values, the second an error, as Thilo said above:

function func()
    err = ""
    try
        error()
    catch e
        err = "Error string"
    finally
        10, err
    end
end

foo, errstring = func()

There is a way to do what you should probably not do. Use a global for foo, and assign to the global in the function instead of via the return value, as in:

foo = 2

function func()
    global foo = 10
    try
        error()
    catch e
        throw(e)
    finally
        10
    end
end


function thrower()
    try
        func()
    catch
        println("foo = $foo")
    end
end

thrower()

Upvotes: 2

Related Questions