1

I would like for the loop to keep going even exception is generated at first iteration. How to do this?

mydict = {}
wl = ["test", "test1", "test2"]
    
try:
  for i in wl:
   a = mydict['sdf']
   print(i)
            
except:
       # I want the loop to continue and print all elements of list, instead of exiting it after exception
       # exception will occur because mydict doesn't have 'sdf' key
    pass
1
  • 8
    Move try / except inside loop body Commented Aug 3, 2020 at 4:51

3 Answers 3

1

You can use dict.get(). It will return None if the key not exist. You can also specify default value in dict.get(key, default_value)

for i in wl:
    a = mydict.get('sdf')
    print(i)
Sign up to request clarification or add additional context in comments.

Comments

0

The best I can advice is to move the try inside the loop as below:

mydict = {}
wl = ["test", "test1", "test2"]
for i in wl:
    try:
        a = mydict['sdf']
        print(i)

    except:
        continue

3 Comments

This is incorrect. The print will be skipped.
Those two lines of code are independent, so you could just move the print to be first.
Also, using a bare except that catches all exceptions is bad practice. Only catch the exceptions that you know might be raised.
0

This is my approach for your problem
Hope its work for you as you want

mydict = {}
wl = ["test", "test1", "test2"]

for i in wl:
    try:
        a = mydict['sdf']
    except:
        pass
    print(i)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.