julia: display the `catch` error in control flow

Viewed 954

Consider the following try/catch flow

function test(x)
    try x^3
        if x < 0; error("i only accept x >= 0"); end
        return x^3
    catch
        return abs(x)^3
    end
end

How can I display the error message (and stack trace) in the case test(-2) # == 8? In this case I know the error, but if it's a more complicated function with asserts etc, I'd like to know what specifically failed.

Trying rethrow() needs to be done in the try-catch block, but I still want a return value.

1 Answers

You can save the Exception into a variable after writing the variable name of your choice right after catch. error creates an ErrorException. You can see the fields of this Exception using fieldnames(ErrorException). The msg field gives you the message you passed to error. Alternatively, you may use showerror method.

function test(x)
    try x^3
        if x < 0; error("i only accept x >= 0"); end
        return x^3
    catch e
        showerror(stdout, e)
        # or 
        println(e.msg)
    end
end

For the stack trace, you may use stacktrace(catch_backtrace()). We pass catch_backtrace to stacktrace, because what we usually want is to obtain the stack trace of the context of the most recent exception and not the current context.

Related