I’m trying to use a try/catch block to debug something that is failing. The code looks something like
df = DataFrame(...)
for row in eachrow(df)
try
variable = row[:1]
....(some code)....
catch
println(variable)
end
end
When I do this, the variable printed in the catch block appears to not be what is in set in the try block. Is this the expected behavior?
Why not make a minimal working example that shows the unexpected behavior? It makes things much easier.
1 Like
Sorry, I thought it would be a simple “you’re doing it wrong” kind of answer…
Here is my code
df = DataFrame(col1=[1,2,3],col2=[6,7,8])
var = 999
for row in eachrow(df)
try
var = row[:1]
println("try $var")
if var > 2
throw(ErrorException("test"))
end
catch
println("catch $var")
end
end
Here are the results
try 1
try 2
try 3
catch 999
Shouldn’t it be:
try 1
try 2
try 3
catch 3
try
and catch
each have their own scope, and local variables aren’t implicitly visible between scopes. Instead, mark the shared variable as local
to the parent scope:
using DataFrames
df = DataFrame(col1=[1,2,3],col2=[6,7,8])
var = 999
for row in eachrow(df)
local var
try
var = row[:1]
println("try $var")
if var > 2
throw(ErrorException("test"))
end
catch
println("catch $var")
end
end
Thanks, I appreciate the help.
Now I accept that this is the answer, but this bothers me a bit. This is really one block statement with one END statement isn’t it? So I would have thought that these are part of the same scope. It seems unintuitive to me that they have different scopes.
Other languages like python don’t seem to behave this way as far as I know.
I’m really trying to migrate to Julia, because Python syntax just annoys me, but the barrier to entry seems quite high. I wish there was some “Dummy” or “Easy” mode that people like me could use that would operate in a simpler, more intuitive manner, even if the performance were degraded a bit.
Anyways, onward…
Fortunately, this mode exists!
using DataFrames, SoftGlobalScope
df = DataFrame(col1=[1,2,3],col2=[6,7,8])
var = 999
@softscope for row in eachrow(df)
try
var = row[:1]
println("try $var")
if var > 2
throw(ErrorException("test"))
end
catch
println("catch $var")
end
end
Great!
As the self appointment representative of all of the dummies out there, I thank you and the author of this package.
As has been discussed here this package, in some form, will become the default in all interactive julia environments (including the REPL). We are all idots!