Error messages in for loops

I was just working on my code and got an error where the stacktrace pointed to a line inside a for loop. To debug the code I was about to print the for-loop-variable to find out in which iteration the error happened.

Wouldn’t it be easier if the stacktrace automatically displayed the current value of the for-loop-variable? Is this something other languages do or is a dedicated debugger needed for this?

You’ll need a debugger for this - exception handling has, aside from where the exception got thrown and what kind of call stack exists, no knowledge about particular code that threw the exception.

(Though it could be theoretically done, I think it’s infeasible to do so in julia since you’d have to modify the compiler to keep track of loop variables and iteration state (which may be optimized away entirely).)

So would this mean that Julia’s performance would suffer, if this "feature“ was implemented?

Not necessarily (at least off the top of my head I don’t want to lean either way). The problem is though that identifying which specific variables in any given loop is relevant for a throwing action is very hard to do - at compile time you don’t know which variables will be necessary to keep track of, so the compiler has no choice but to keep track of all of them (which could impede performance) and may not be possible in all cases (e.g. what if some variables are only relevant in a subset of iterations? Do you allocate space for all of them during all iterations?).

It’s easier if you’re in an interpreted language, since at any given point you know exactly which variables are relevant at that moment (because you’re operating at runtime of the program) - but that’s not the case for compiled languages like julia.

It’s not so much that performance would suffer, the problem is more that the compiler is allowed to make large changes to your code (like removing a loop entirely or combining multiple iterations into one). These changes mean that the code that actually gets executed doesn’t correspond 1 to 1 with the code you wrote.

It would only do those things if it knows the loop won’t throw. This is why @inbounds is necessary for SIMD, for example.