Make python code continue after exception

Question:

I’m trying to read all files from a folder that matches a certain criteria. My program crashes once I have an exception raised. I am trying to continue even if there’s an exception but it still stops executing.

This is what I get after a couple of seconds.

error <type 'exceptions.IOError'>

Here’s my code

import os 
path = 'Y:\Files\'
listing = os.listdir(path)
try:
    for infile in listing:
        if infile.startswith("ABC"):
            fo = open(infile,"r")
            for line in fo:
                if line.startswith("REVIEW"):
                    print infile
            fo.close()
except:
    print "error "+str(IOError)
    pass
Asked By: Ank

||

Answers:

Put your try/except structure more in-wards. Otherwise when you get an error, it will break all the loops.

Perhaps after the first for-loop, add the try/except. Then if an error is raised, it will continue with the next file.

for infile in listing:
    try:
        if infile.startswith("ABC"):
            fo = open(infile,"r")
            for line in fo:
                if line.startswith("REVIEW"):
                    print infile
            fo.close()
    except:
        pass

This is a perfect example of why you should use a with statement here to open files. When you open the file using open(), but an error is catched, the file will remain open forever. Now is better than never.

for infile in listing:
    try:
        if infile.startswith("ABC"):
            with open(infile,"r") as fo
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
    except:
        pass

Now if an error is caught, the file will be closed, as that is what the with statement does.

Answered By: TerryA

You’re code is doing exactly what you’re telling it to do. When you get an exception, it jumps down to this section:

except:
    print "error "+str(IOError)
    pass

Since there’s nothing after that, the program ends.

Also, that pass is superfluous.

Answered By: Brendan Long

Move the try/except inside the for loop.
Like in:

  import os 
    path = 'C:\'
    listing = os.listdir(path)
    for infile in listing:
        try:    
            if infile.startswith("ABC"):
                fo = open(infile,"r")
                for line in fo:
                    if line.startswith("REVIEW"):
                        print infile
                fo.close()
        except:
              print "error "+str(IOError)
Answered By: Rami

As per strictest interpretation of the question "continue even if there’s an exception". Python gives us a keyword "finally" which executes a block of code no matter what precedes it. The only issue with this method will run a block of code regardless of the type of error, which might not be desirable for all cases.

try:
  unreal = 3/0 # raises divide by zero exception
  print(unreal)

# handles zerodivision exception
except :
  print("Can't divide by zero, 0 has no multiplicative inverse")

finally:
# this block is always executed
  print("Brahmagupta claimed that “zero divided by a zero is zero.”) 
Answered By: Jose Urena
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.