Try/catch issue

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:

A=[1,2]'
for i = 1:10
    try
        B=[1,2,3,4] #Creating an error in purpose for the example
    catch B
        if B > 2 # if error
            B=[1,2] # fix error
            A=vcat(A,B')
        else # else
            A=vcat(A,B')
        end
    end
end
A

Before anything, you should start to indent your code. That makes your code much more readable and it’ll be easier to spot bugs.

4 Likes

Why is this an error? (It shouldn’t.)

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.)

3 Likes