pyjulia icon indicating copy to clipboard operation
pyjulia copied to clipboard

report line number of julia exception

Open bernstei opened this issue 2 years ago • 3 comments

It would be very helpful if julia.Main.eval(str) reported the line number in the code string that raised the exception, as opposed to just repeating back the whole string. Is there any way to extract that information from the julia exception so it can be printed in julia.core.py::check_exception?

bernstei avatar Mar 03 '23 22:03 bernstei

We might be able to do it if we wrap the string in a begin ... end.

julia> Meta.parse("""
       begin
           println("Hello")
           error()
       end
       """) |> eval
Hello
ERROR: 
Stacktrace:
 [1] error()
   @ Base ./error.jl:44
 [2] top-level scope
   @ none:3

mkitti avatar Mar 05 '23 09:03 mkitti

Thanks. Let me see if that works in my use case, too.

bernstei avatar Mar 06 '23 14:03 bernstei

Just wrapping in begin/end isn't enough to modify the error message printed as part of the julia.core.JuliaError message, although I realize now that I'm not sure if you meant this to be the entire solution, or merely a part that'd make it easier to extract the line number.

What I've done for now is wrap my julia code snipped in a try/catch, with this catch block

catch e
    throw(error(string(e) * " in julia code location " * string(stacktrace(catch_backtrace()))))
end

This appends the julia code line to the error message, which is then printed by python as part of the JuliaError object. It does make the line number off by one, because of the try line, so it can't trivially be done as part of the julia python package, unless you want to edit the string returned by the JuliaError object to modify the line number, which would be a pretty ugly solution.

bernstei avatar Mar 06 '23 14:03 bernstei