Display full error message, and continue

I want to catch an error, display the full error message, and then continue execution (to return whatever data was produced before the error. So I code (MWE)

v = Vector{Vector{Float64}}(undef,3)
try
    v[2]
catch err
    print("Ah... hang on a sec\n")
    display(err)
    print("No sweat, we just continue\n")
end

However this just displays

UndefRefError()

and not the full

ERROR: UndefRefError: access to undefined reference
Stacktrace:
 [1] getindex(A::Vector{Vector{Float64}}, i1::Int64)
   @ Base .\array.jl:801
 [2] top-level scope
   @ none:1

that I want to show.

How can I do that?

:slightly_smiling_face:

Base.show_backtrace(stdout, backtrace()) is one way, but be aware that this is not the same as the above. The regular stacktrace printing in the REPL filters a few REPL specific things.

Usually it’s better to handle exceptions than print & ignore though.

1 Like

Hi Sukera,

Perfect, many thanks!

I did indeed ponder the “to error or not to error” question. In my real world problem, my function fills a vector, element by element with precious results. But then the process may fail. If this occurs I want
a) to provide full diagnosis data to the user
b) stop computing the further elements of the vector
c) return the vector, half filled as it is.
The last point is important, as I see it, I need to return not throw my way out of the function, so that I can make the half filled vector available to the caller. Yes, this implies that the caller of my function must check for half filed vector and act accordingly…

If there is a smart pattern to handle that, I am curious to learn!
:grinning:

In case anyone is interested: given a function that fills in an array with precious result, but may error halfway, how to I get hold of the data computed before the failure?

If the data is to be returned by a function, but the function throws an error, the return variable is not assigned in the calling namespace.

The tric is to make the function a mutating function: the caller allocates, passes the undef’ed array to the function, which fills half the array before throwing an error: in the caller’s namespace, the array is available and half filed. There’s my pattern!