# Quit the loop if encounter error message

First define length-component error (personal term) : This is an error when we want to get n-th component of a list if n is bigger then the length of the list. For example, Range[5][[7]] yields {1, 2, 3, 4, 5}[[7]] but with an error message.

Is there an option (I mean SetOptions) to quit the loop, if length-component error occurs? (Or any kind of error that yields an error message)

You can understand my question easily with screenshots. There are three codes.
Note that MyList = {1, 2, 3, 4, 5}; for all 3 codes. If you think the best is Code 2, I would appreciate it if you wrote so.

Code 1 :

Code 2 :

Code 3 :

To exit evaluation when a message is encountered, use Enclose together with ConfirmQuiet:

In[121]:= Enclose[n = 1;
While[n < 10, Print[ConfirmQuiet[MyList[[n]]]]; ++n]]

During evaluation of In[121]:= 1

During evaluation of In[121]:= 2

During evaluation of In[121]:= 3

During evaluation of In[121]:= 4

During evaluation of In[121]:= 5

Out[121]= Failure["ConfirmationFailed", <|...|>]

• Thank you! As my wish, the answer is not about ignoring messages. CPU really stops when it encounters error message. Commented Aug 26, 2022 at 15:53

Loops are seldom used in MMA. Most of the time loops ca be avoided and replaced by more efficient constructs. However, if you insist on using loops:

At the start of the loop you already know the length of the list. Therefore create a loop with a fixed number of repetitions. Use Do or For. E.g. using Do:

list = {1, 2, 3, 4, 5};
Do[Print[list[[i]]], {i, Length[list]}]


Or with For:

For[i = 1, i <= Length[list], i++ , Print[list[[i]]]]

• Thank you, in fact what I wanted is hard to do with Do.. it is hard to know when it ends. I simplified the example to make it easier to ask. Commented Aug 26, 2022 at 15:50

1.

If we want to avoid a looping-construct we can use Query instead of Part. For non-existing elements Query returns a Missing-object which can be deleted with DeleteMissing.

list = Range[5];

Query[Range @ 7] @ list


{1, 2, 3, 4, 5, Missing["PartAbsent", 6], Missing["PartAbsent", 7]}

DeleteMissing @ Query[Range @ 7] @ list


{1, 2, 3, 4, 5}

2.

Using LookupPart by Richard Hennigan (Wolfram Research)

part = ResourceFunction["LookupPart"];

part[list, 1 ;; UpTo @ 7]


{1, 2, 3, 4, 5}

You can do the following:

n = 1; While[n < 10, If[MemberQ[Outer[List, Ordering[MyList]], {n}] ===True, Print[MyList[[n]]], Break[]]; ++n]