I am new in Julia and I am trying to understand the way that try/catch control flow is working.
I need to handle possible errors inside a for loop, correct them and finally do what I should do if there was no error.
However for some reason I don’t manage to do it.
Thanks in advance for your help.
Please find below the conceptual approach I am trying to do:
for i = 1:10
B=[1,2,3,4] #Creating an error in purpose for the example
if B > 2 # if error
B=[1,2] # fix error
else # else
Why is this a check for error? I mean if you are in the catch block you have already caught an error. And B is the exception here and probably doesn’t compare to 2. (Not that [1, 2, 3, 4] does either…)
I am guessing but it seems that you do not understand what a exception is or what try-catch is. You seems to think it’s a syntax to help you do branch/check, it’s not. It’s a way to catch exceptions that you’ve thrown. So B = [1, 2, 3, 4], however unexpected it is for the purpose of your code, will not throw an error and won’t do anything in the catch block, which includes both branches of the if. And the catch B has nothing to do with your B = [1, 2, 3, 4].
If you actually have an exception to catch, you should post the real code. If, IMO more like, you are just looking for a way to check for unexpected value and correct for them, just use branches. You can just get rid of the try-catch completely. You’ll probably also need to fix the B > 2 since that might give you an actual error. I’m guessing you want length(B) > 2 here.
And if my guess is wrong, you can ignore all this but you should describe in detail what is your expected behavior (what do you mean by “handle possible errors”, “correct them”, what’s the expected output, etc.)