Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
abruptly leaving try/except
#1
a while back, in a discussion that involved try/except constructs, someone said that it was a bad idea to get out of a try/except with statements like return and continue. so i have been avoiding that by setting variables to indicate if i need to do something, then after the try/except, testing that variable and maybe doing that action.

i am cleaning up some code, today, that is like that. in a loop iterating over a list of files i perform os.lstat() on each file. if it fails i just want to skip that file. so my code looks like this:

    for fn in file_list:
        try:
            s = os.lstat(fn)
            x = False
        except:
            x = True
        if x:
            continue
        ...
today this "bothered" me and i was wondering if i really needed to do that, or if i could simply do:

    for fn in file_list:
        try:
            s = os.lstat(fn)
        except:
            continue
        ...
which seems like the "right way" to do this.

anyone know what i should be doing? should i be reviewing all my existing code for try/except cases like this?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Use pass
import os

with os.scandir('.') as it:
    for file in it:
         try:
            info = os.lstat(file)
            print(info)
         except Exception:
            pass
In newer Python version after 3.4--> there is also.
from contextlib import suppress
import os

with suppress(OSError):
    info = os.lstat(file)
    print(info)
So all OSError will be skipped on code that inside the with block.
Reply
#3
i don't understand your code. i don't see how it skips that iteration when an exception takes place, as in, making sure that the code below is only run when no exception takes place. do i need to use with even when my list is a list?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
Think of it like this.
Error:
>>> 1 / 0 Traceback (most recent call last): File "<string>", line 305, in runcode File "<interactive input>", line 1, in <module> ZeroDivisionError: division by zero
So in a list like this in a loop.
lst = [0, 0, 0, 0, 1, 2, 0, 0, 4]
We want to to skip all 0 which give ZeroDivisionError and get to get result where there is no error.
>>> 1 / 1
1.0
This can bye files or what ever that generate a error,that's want to be bypassed.
def foo():
    lst = [0, 0, 0, 0, 1, 2, 0, 0, 4,]
    l = []
    for i in lst:
        try:
            n = 1 / i
            l.append(n)
        except ZeroDivisionError:
            return('Cannot divide by 0')
    return l

print(foo())
Output:
Cannot divide by 0
def foo():
    lst = [0, 0, 0, 0, 1, 2, 0, 0, 4,]
    l = []
    for i in lst:
        try:
            n = 1 / i
            l.append(n)
        except ZeroDivisionError:
            pass
    return l

print(foo())
Output:
[1.0, 0.5, 0.25]
Reply
#5
i still don't understand your logic. are you trying to replicate my first block of code?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#6
he's showing how to use suppress
as an alternative
Reply
#7
What's wrong with using continue in the try...except statement? I'm doing this all the time.
Reply
#8
(Feb-19-2018, 09:32 PM)Gribouillis Wrote: What's wrong with using continue in the try...except statement? I'm doing this all the time.
i really don't know ... if there is any issue at all. it's just that some dialog i once had or read a long time ago left me with the impression that some state of the try/except was leftover that could cause problems (i can't even remember what they were) if the try/except didn't fall through one way or the other. though this seemed odd, and when i have done continue or return in a try/except (on either side) i say no issues, i have always just set things to indicate what to do and do them after try/except based on what was set.

maybe it was just a big misunderstanding on my part.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#9
(Feb-19-2018, 09:32 PM)Gribouillis Wrote: What's wrong with using continue in the try...except statement? I'm doing this all the time
Nothing wrong just that pass is much more common in try...except.
There is a little difference:
continue will jump back to the top of the loop.
pass will continue processing.

So if look in Doc they always use pass when describing suppresses any of the specified exceptions.
So if using code example over.
from contextlib import suppress
import os
 
with suppress(OSError):
    info = os.lstat(file)
    print(info)
Writing the same as over with try...except then is pass as in Doc.
import os

try:
    info = os.lstat(file)
    print(info)
except OSError:
    pass
Reply
#10
the apparent need of a pass statement is because python does not allow empty blocks of code. you can leave out else: but if you put it in, it must have at least one line of code. and you cannot leave out except: after a try: block.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020