How to print a backtrace?

How can I print an error and backtrace from within a catch block, the same as if it had not been caught in the REPL?

You can use the function Base.showerror to show the error message and Base.show_backtrace(io, Base.catch_backtrace()) to print the stacktrack from where the current error was thrown:

julia> try
           error("some error")
       catch e
           Base.printstyled("ERROR: "; color=:red, bold=true)
           Base.showerror(stdout, e)
           Base.show_backtrace(stdout, Base.catch_backtrace())
       end
ERROR: some error
Stacktrace:
  [1] error(s::String)
    @ Base ./error.jl:33
  [2] top-level scope
    @ REPL[8]:2
  [3] eval
    @ ./boot.jl:373 [inlined]
  [4] eval_user_input(ast::Any, backend::REPL.REPLBackend)
    @ REPL ~/.julia/juliaup/julia-1.7.1+0~aarch64/share/julia/stdlib/v1.7/REPL/src/REPL.jl:150
  [5] repl_backend_loop(backend::REPL.REPLBackend)
    @ REPL ~/.julia/juliaup/julia-1.7.1+0~aarch64/share/julia/stdlib/v1.7/REPL/src/REPL.jl:244
  [6] start_repl_backend(backend::REPL.REPLBackend, consumer::Any)
    @ REPL ~/.julia/juliaup/julia-1.7.1+0~aarch64/share/julia/stdlib/v1.7/REPL/src/REPL.jl:229
  [7] run_repl(repl::REPL.AbstractREPL, consumer::Any; backend_on_current_task::Bool)
    @ REPL ~/.julia/juliaup/julia-1.7.1+0~aarch64/share/julia/stdlib/v1.7/REPL/src/REPL.jl:362
  [8] run_repl(repl::REPL.AbstractREPL, consumer::Any)
    @ REPL ~/.julia/juliaup/julia-1.7.1+0~aarch64/share/julia/stdlib/v1.7/REPL/src/REPL.jl:349
  [9] (::Base.var"#930#932"{Bool, Bool, Bool})(REPL::Module)
    @ Base ./client.jl:394
 [10] #invokelatest#2
    @ ./essentials.jl:716 [inlined]
 [11] invokelatest
    @ ./essentials.jl:714 [inlined]
 [12] run_main_repl(interactive::Bool, quiet::Bool, banner::Bool, history_file::Bool, color_set::Bool)
    @ Base ./client.jl:379
 [13] exec_options(opts::Base.JLOptions)
    @ Base ./client.jl:309
 [14] _start()
    @ Base ./client.jl:495
3 Likes

Amazing, thanks!

More simply, you can do:

Base.showerror(stdout, e, Base.catch_backtrace())
2 Likes