# 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[] yields {1, 2, 3, 4, 5}[] 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:= Enclose[n = 1;
While[n < 10, Print[ConfirmQuiet[MyList[[n]]]]; ++n]]

During evaluation of In:= 1

During evaluation of In:= 2

During evaluation of In:= 3

During evaluation of In:= 4

During evaluation of In:= 5

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

• Thank you! As my wish, the answer is not about ignoring messages. CPU really stops when it encounters error message. 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. Aug 26, 2022 at 15:50

You can do the following:

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