Try/catch behavior with undefined variables

Hello all, I was very recently introduced to Julia, and I’ve been playing around with the REPL when I ran into something that I found odd.

Maybe I’m just used to how some other languages work, but the behavior of try/catch surprised me. Here’s a simple example:

f(z) = try
  z + 1
catch
  println("error")
end

…works fine if z is numeric (or even a character, which I find neat). Should z be something non-mathematically-inclined (such as a string), “error” is printed as one would expect. However, should z be an undefined variable, rather than printing the error notice, it generates a stack trace:

f(i)
ERROR:UndefVarError: i is not defined
Stacktrace:
  [1] top-level scope at none:0

I would have expect this still to print “error” instead of crashing. Is this just how Julia works (requiring other code to catch that circumstance) or am I misusing the command somehow?

I’ve poked around here and didn’t find a similar topic, but apologies if I’ve overlooked it.

Thanks all!

The function and argument expressions are evaluated before the function is called. So the expression i is evaluated and errors due to i being undefined before f is even called so the definition of f is irrelevant. The error is in the caller, not in the function. By comparison, if i has a value but doesn’t support the i + 1 operation then the caller is fine: they called a function that claims to take any kind of value, after all, and the error occurs during the evaluation of f inside a try block so it would be caught.

This is all quite standard; I’d be interested in hearing about other languages doing something else here. It would seem that they would need to do some kind of lazy evaluation for this to behave the way you seem to expect. Are you by any chance coming from R?

2 Likes