One (dirty) way to do it is to use tryCatch with an empty function for error handling. For example, the following code raises an error and breaks the loop :

for (i in 1:10) {
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
Erreur : Urgh, the iphone is in the blender !

But you can wrap your instructions into a tryCatch with an error handling function that does nothing, for example :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

But I think you should at least print the error message to know if something bad happened while letting your code continue to run :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
ERROR : Urgh, the iphone is in the blender ! 
[1] 8
[1] 9
[1] 10

EDIT : So to apply tryCatch in your case would be something like :

for (v in 2:180){
    tryCatch({
        mypath=file.path("C:", "file1", (paste("graph",names(mydata[columnname]), ".pdf", sep="-")))
        pdf(file=mypath)
        mytitle = paste("anything")
        myplotfunction(mydata[,columnnumber]) ## this function is defined previously in the program
        dev.off()
    }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}
Answer from juba on Stack Overflow
🌐
DevGenius
blog.devgenius.io › python-how-can-i-skip-an-iteration-in-a-for-loop-if-it-has-an-error-eb072c3aaa84
Python | how can I skip an iteration in a for loop if it has an error | by Moamen Elabd | Dev Genius
May 17, 2023 - Easiest way to solve this issue is to create a try | except lines in the for loop itself, so when the For loop will run it will try the code there but if has an error, instead of breaking the loop you can try another code or Just pass the iteration
Top answer
1 of 2
206

One (dirty) way to do it is to use tryCatch with an empty function for error handling. For example, the following code raises an error and breaks the loop :

for (i in 1:10) {
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
Erreur : Urgh, the iphone is in the blender !

But you can wrap your instructions into a tryCatch with an error handling function that does nothing, for example :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

But I think you should at least print the error message to know if something bad happened while letting your code continue to run :

for (i in 1:10) {
  tryCatch({
    print(i)
    if (i==7) stop("Urgh, the iphone is in the blender !")
  }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}

[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
ERROR : Urgh, the iphone is in the blender ! 
[1] 8
[1] 9
[1] 10

EDIT : So to apply tryCatch in your case would be something like :

for (v in 2:180){
    tryCatch({
        mypath=file.path("C:", "file1", (paste("graph",names(mydata[columnname]), ".pdf", sep="-")))
        pdf(file=mypath)
        mytitle = paste("anything")
        myplotfunction(mydata[,columnnumber]) ## this function is defined previously in the program
        dev.off()
    }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}
2 of 2
28

Here's a simple way

for (i in 1:10) {
  
  skip_to_next <- FALSE
  
  # Note that print(b) fails since b doesn't exist
  
  tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
  
  if(skip_to_next) { next }     
}

Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b) with any code you want. You can also wrap many lines of code in { and } if you have more than one line of code inside the tryCatch

Discussions

Help me skip the current iteration in for loop if exception found
syntax - For each item in array { assign write range . . . } This is surtrounded by try catch suppose if an exception comes then can I use break activity in the catch block to skip current iteration and move to next iteration of for each… or the break activity will exit the for each loop ... More on forum.uipath.com
🌐 forum.uipath.com
5
1
November 19, 2019
skipping an error to continue iterations
Hi I am trying to run a large chunk of code inside for loop and store the output in matrices. There is an error message for certain samples and I want to skip the iterations with error message and move to next iteration. Can anyone please explain, how can I do that. More on forum.posit.co
🌐 forum.posit.co
0
0
September 9, 2021
How to skip iteration immediately in VBA for loop if any error occurs - Stack Overflow
I have for loop in VBA that goes through xlsx. files placed in one folder. The script is about to open each file from 1000 input files, extract information and save in extract files. The thing is u... More on stackoverflow.com
🌐 stackoverflow.com
How to use VBA "for loop" to skip error and keep doing next ...
🌐 answers.microsoft.com
March 4, 2017
🌐
Quora
quora.com › How-do-you-skip-an-error-and-continue-to-run-for-a-loop-and-then-continue-to-the-next-line-Python-development
How to skip an error and continue to run for a loop and then continue to the next line (Python, development) - Quora
Answer (1 of 4): Depends on the severity of the “error”. If something’s raising an Exception, that’s what try/except is all about. Start here: https://realpython.com/python-exceptions/
🌐
UiPath Community
forum.uipath.com › learning hub › academy feedback
Help me skip the current iteration in for loop if exception found - Academy Feedback - UiPath Community Forum
November 19, 2019 - . . } This is surtrounded by try catch suppose if an exception comes then can I use break activity in the catch block to skip current iteration and move to next iteration of for each… or the break activity will exit the for each loop ...
🌐
LearnDataSci
learndatasci.com › solutions › python-continue
Python Continue - Controlling for and while Loops – LearnDataSci
Once our for loop reaches minus nine, our Python script crashes. The reason that our program crashes is math.sqrt doesn't work with negative numbers. One way of avoiding this error is by using continue like so: for num in num_list: if num < 0: # check if the number is negative print(f"{num} is negative, so it has been skipped") continue print(f"The square root of {num} is {math.sqrt(num)}")
🌐
DataCamp
campus.datacamp.com › courses › intermediate-r-for-finance › loops-3
Break and next | R
# Print apple ___ # Loop through apple. Next if NA. Break if above 117. for (value in apple) { if(is.na(___)) { print("Skipping NA") next } if(value > ___) { print("Time to sell!") break } else { print(___) } }
🌐
Posit Community
forum.posit.co › general
skipping an error to continue iterations - General - Posit Community
September 9, 2021 - Hi I am trying to run a large chunk of code inside for loop and store the output in matrices. There is an error message for certain samples and I want to skip the iterations with error message and move to next iteratio…
🌐
Stack Overflow
stackoverflow.com › questions › 74811095 › how-to-skip-iteration-immediately-in-vba-for-loop-if-any-error-occurs
How to skip iteration immediately in VBA for loop if any error occurs - Stack Overflow
Public Function TryOpenDoc(byval ipPath as string, byref opDoc as document) as Boolean On Error Resume Next Set opDoc = Workbooks.Open(ipPath) TryOpenDoc = (err.number = 0) on error goto 0 exit function ' so now you can write If TryOpenDoc(sFileoutPut, wb_ouput) then 'Do the happy path stuff else ' do the stuff for a file failing to open end if ... I found that the easiest way to handle this issue isn't through skipping iteration but simply adding CorruptLoad argument to the Open function.
Find elsewhere
🌐
R-bloggers
r-bloggers.com › r bloggers › skip errors in r loops by not writing loops
Skip errors in R loops by not writing loops | R-bloggers
December 21, 2017 - As you see, even though the fourth element could have been computed, the error made the whole loop stop. In such a simple example, you could correct this and then run your function. But what if the list you want to apply your function to is very long and the computation take a very, very long time? Perhaps you simply want to skip these errors and get back to them later. One way of doing that is using tryCatch(): result = vector("list", length(some_numbers)) for(i in seq_along(some_numbers)){ result[[i]] = tryCatch(some_function(some_numbers[[i]]), error = function(e) paste("something wrong here")) } print(result) ## [[1]] ## [1] -1.378405 ## ## [[2]] ## [1] 4.472136 ## ## [[3]] ## [1] "something wrong here" ## ## [[4]] ## [1] -6.480741
🌐
UiPath Community
forum.uipath.com › help
How to skip error message and continue a loop - Help - UiPath Community Forum
June 25, 2019 - Hi everyone, Lets say I do a loop for the list of ID`s to find each ID in some application and do some actions (like clicking on already found ID for more details) after I have found it. When bot runs and it could not proceed because it can not find ID (so there is no ID to click on) “error” ...
🌐
JMP User Community
community.jmp.com › t5 › Discussions › How-do-I-ignore-errors-and-let-the-loop-continue-while-executing › td-p › 227572
Solved: How do I ignore errors and let the loop continue while executing a loop in JSL? - JMP User Community
September 28, 2019 - Thank you very much! ... The easiest way to handle this is to use the Try() function. It allows you to return a value if the statement(s) within the Try() function have an error. You can then detect the error and handle it the way it needs to ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-use-break-continue-and-pass-statements-when-working-with-loops-in-python-3
How To Use break, continue, and pass Statements in Python | DigitalOcean
April 24, 2026 - Continuing to loop would waste time or resources. You’ve already found what you’re looking for. Early exits make the logic easier to understand and maintain. ... pass: The pass statement does nothing; it is used as a placeholder when a statement is syntactically required but no action is needed. For example: for i in range(5): if i == 3: pass # Placeholder for future code print(i) continue: The continue statement skips the rest of the code in the current iteration and moves to the next iteration of the loop.
🌐
Stack Overflow
stackoverflow.com › questions › 58537955 › skip-the-loop-certain-number-of-times-if-a-condition-satisfies-in-a-for-loop
python - skip the loop certain number of times if a condition satisfies in a for loop - Stack Overflow
October 24, 2019 - Actually i = i+3 has no effect in a for loop. you may think that i becomes 2+3=5 but in the next iteration i will be 3. You need to use a hile loop for this. This will do the trick for you: i = 2 while i <= 100: print(i) i = (i + 3) if i % 2 != 0 else (i + 1) ... skipping = 0 for i in range(2, 100): if skipping: skipping -= 1 continue if i % 2 != 0: print(i) skipping = 2 else: print(i)
🌐
Codecademy
codecademy.com › forum_questions › 546d86e87c82cab953000797
Ending a loop, and invoking a loop if an error in the code occurs. | Codecademy
Okay so, I have created my functions outside of the loop now, and it works, but all the examples I see don’t take else statements into consideration, how do I make the else part of the if statement prompt the user again for an integer or float? As well as try again if the code gives an error.