Using Continue in a Try and Except Inside While-Loop

Using continue in a try and except inside while-loop

You can solve the problem by moving the variable assignments into the try block. That way, the stuff you want to skip is automatically avoided when an exception is raised. Now there is no reason to continue and the next prompt will be displayed.

c=0
num2=0
num=raw_input("Enter a number.")
while num!=str("done"):
try:
num=float(num)
c=c+1
num2=num+num2
except:
print "Invalid input"
num=raw_input("Enter a number.")
avg=num2/c
print num2, "\t", c, "\t", avg

You can tighten this a bit further by removing the need to duplicate the prompt

c=0
num2=0
while True:
num=raw_input("Enter a number. ")
if num == "done":
break
try:
num2+=float(num)
c=c+1
except:
print "Invalid input"
avg=num2/c
print num2, "\t", c, "\t", avg

While loop continue not working inside try, except, finally

finally will always run after the try-except. You want else, which will run only if the try-block doesn't raise an exception.

By the way, minimize the code in a try-block, to avoid false-positives.

while True:
inp = input("Enter number: ")
try:
num = int(inp)
except ValueError:
print('Error: Please enter number only')
continue
else:
print(num)
break
print('This will never print') # Added just for demo

Test run:

Enter number: f
Error: Please enter number only
Enter number: 15
15

Note that the continue is not actually needed in your example, so I added a demo print() at the bottom of the loop.

while loop with try/exception stay in loop until read all rows of df / ignore exception

Once continue is called, it will skip back to the top before i += 1 is called. Try moving that statement higher up, something like:

i=7
while i<10:
try:
Repo.clone_from(df.git_url[i],repo_dir) #clone repositores for each url
except:
print("error")
i += 1
continue
else:
for f in glob.iglob("repo_dir/**/*.rb"):
txt = open(f, "r")
# let's say txt is a code file that I want to extract data from
for line in txt:
print(line)
shutil.rmtree(repo_dir)
os.makedirs(repo_dir)
i += 1

That way it won't get stuck on the problematic iteration, let me know how this goes :)

How do I continue my try/catch in my while-loop

Raise ValueErrors so that your except block will catch these too:

if chips_input < 1:
raise ValueError("Sorry, you have to enter a number bigger than 1.")
if chips_input > chip_amount:
raise ValueError(f'Sorry, you have to enter a number less than {chip_amount}.')

Try and Except inside of a While Loop - Opening files

It would make more sense to check with os.path.isfile

import os

while True:

input_file = input('Enter the name of the Input File: ')
if not os.path.isfile(input_file):
print('File not found. Try again.')
continue
break

print('File found!')

error in while loop combined with try-except

The problem is that you are "protecting" the while loop where the name is simply asked. You could instead put the reading also inside the try/except to handle the problem:

while True:
try:
file_to_open = input("insert the file you would like to use with its extension: ")
with open(file_to_open) as f:
words = word_tokenize(f.read().lower())
break
except FileNotFoundError:
print("File not found.Better try again")

I put my try catch in a do while loop, but the commands after the do-while loop continue running even though there is an exception caught

After the first input (100) you set checker = 0;. Since the value is too large you print "Bruh that's not valid" and stay within the outer loop.

That means that you read another value (five) which leads to the exception. However, since checker is already 0 (from the first pass) the inner loop is not repeated.

You need to reset checker to 1 before each start of the inner loop:

    do {

checker = 1;
do {
try {
userInput = in.nextInt();
checker = 0;
}
catch (Exception e) {
System.out.println("Exception detectedddd");
in.nextLine(); // This line is to *clear the buffer* for Scanner
}
} while (checker == 1);

//... remainder of the outer loop
} while (validUserInput == 0);


Related Topics



Leave a reply



Submit