Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make python code continue after exception

Tags:

python

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 
like image 542
Ank Avatar asked Sep 25 '13 00:09

Ank


People also ask

How do you continue after raising exception in Python?

Perhaps after the first for-loop, add the try/except . Then if an error is raised, it will continue with the next file. 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.

How do I continue a program after catching an exception?

Resuming the program When a checked/compile time exception occurs you can resume the program by handling it using try-catch blocks. Using these you can display your own message or display the exception message after execution of the complete program.

Does Python continue after try except?

If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try/except block.


1 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.

like image 51
TerryA Avatar answered Sep 29 '22 06:09

TerryA