How to find the error line using try/catch statements?

Hi,
I want to get the line number of an error using try/catch statements.

try
[my_function]

catch err
println(err) #this only shows the name of the error
#i want to print the line number of the error

I hope you can help me.

3 Likes

You want rethrow

julia> function foo()
           throw(error("hello"))
       end;

julia> try
           foo()
       catch e
           println("foo threw an error")
           rethrow(e)
       end
foo threw an error
ERROR: hello
Stacktrace:
 [1] error(s::String)
   @ Base .\error.jl:33
 [2] foo()
   @ Main .\REPL[33]:2
 [3] top-level scope
   @ REPL[34]:2
6 Likes

If you do not want to rethrow error, then you can use catch_backtrace() with any of logger macros

julia> try
           throw(error("hello"))
       catch err
           @error "ERROR: " exception=(err, catch_backtrace())
       end
┌ Error: ERROR:
│   exception =
│    hello
│    Stacktrace:
│    [1]  Base ./client.jl:485
│      _start()
│    [2]  Base ./client.jl:302
│      exec_options(opts::Base.JLOptions)
│    [3]  Base ./client.jl:372
│      run_main_repl(interactive::Bool, quiet::Bool, banner::Bool, history_file::Bool, color_set::Bool)
│    [4]  ./essentials.jl:706 [inlined]
│      invokelatest
...
4 Likes

Thanks @pdeffebach, your solution does work.
Do you know how to try with another option when first doesn’t work?
For example:

try
var = first_option #this variable sometimes works, but in some cases throw an error

#so, when this var throw an error, I want to do other thing.
"other option":
var = second_option

In others words, i want try with an option, but if this option throw me an error, i want to do the second option, that I know its work. I hope you understand me.

Have you tried a simple if condition?

I tought do that, but I don’t know how to put it in the code.
It’s something like this?

if first_option == error
      var = second_option
else
      var = first_option

Is there any “is error” function?
How would you do it?

Something like this may or may not be what you’re after: difficult to tell without context.

The other thing is since you double-posted, perhaps you could delete the other post.

function foo1()
    throw(error("first error caught!"))
end

function foo2()
    throw(error("second error caught!"))
end


try
    foo1()
catch e
    print("foo1 just threw an error! will try foo2\n")
    try 
        foo2()
    catch e
        print("oops! foo2 also threw an error!!")
        rethrow(e)
    end
end