Handle Exception in Python - python

Code:
genders=[]
for image in os.listdir('Face'):
try:
gender = int(image.split('_')[1])
except ValueError:
pass
genders.append(gender)
Trying to add int values of string in list.
Raises Value error
ValueError: invalid literal for int() with base 10: ''
so for example : imageName_1 get that one and add to a list. but sometimes after _ there is no number. so i want to catch that image and delete it but don't want to stop the iteration.

Maybe a small change in the code will work
genders=[]
for image in os.listdir('Face'):
try:
gender = int(image.split('_')[1])
genders.append(gender)
except ValueError:
pass

Using continue statement will allow you to continue iteration.
genders=[]
for image in os.listdir('Face'):
try:
gender = int(image.split('_')[1])
except ValueError:
continue
genders.append(gender)

import os
genders=[]
for image in os.listdir('Face'):
try:
genders.append(int(image.split('_')[1]))
except (ValueError, IndexError):
try:
os.remove(image)
except OSError:
pass

gender is defined in the try clause only, so you can't append it to genders, and you don't need to (because you want to delete the file), so this line should be in the try clause also:
genders=[]
for image in os.listdir('Face'):
try:
gender = int(image.split('_')[1])
genders.append(gender)
except ValueError:
# delete file
os.remove(image)

Related

how to continue processing after exception in python without aborting

I have a block of code where exception is happening for some records while executing an imported method (pls see below). My goal is NOT to stop execution, but perhaps print (to understand what's wrong with the data) some values when in error and continue. I tried various way to use "try...except", but no luck! Can someone pls take a look and suggest? Many thanks in advance!
code below
if student_name not in original_df_names_flat:
for org in orgs:
data = calculate(org, data)
result = imported_module.execute(data) # here's the line where exception happens
return result
else:
return data
if student_name not in original_df_names_flat:
for org in orgs:
data = calculate(org, data)
result = None # May fail to get assigned if error in imported_module
try:
result = imported_module.execute(data) # here's the line where exception happens
except Exception as e:
print(f'{e}') # probably better to log the exception
return result
else:
return data
I guess an exception can occur in 2 places. So try this. It covers your exception line and the other possibility. So your program should keep running.
Secondly I have adjusted the indentation of the second try clause so the loop processes all data in orgs. To return all results I have added a list 'results'.
if student_name not in original_df_names_flat:
results = []
for org in orgs:
try:
data = calculate(org, data)
except Exception as e:
print(str(e))
try:
result = imported_module.execute(data) # here's the line where exception happens
results.append(result)
except Exception as e:
print(str(e))
return results
else:
return data
the below solution took care of the problem:
if student_name not in original_df_names_flat:
for org in orgs:
data = calculate(org, data)
try:
result = imported_module.execute(data) # here's the line where exception happens
except exception as e:
print ("exception happened", e)
pass
return data
return result
else:
return data
the above solution took care of the problem

How to properly handle multiple Runtime errors?

Program description:
Program accepts a file name and a segment, consisting of two numbers (each divided by one space). Then it outputs all lines from existing file where their indicies lie within the given segment.
My solution:
import sys
try:
par = input("Input (<file> <low border of the segment> <high border of the segment>): ").split(' ')
print(17 * '-')
f = par[0]
f_lines = [line.strip("\n") for line in f if line != "\n"]
length = len(f_lines)
if (par == ''):
raise RuntimeError('Error: undefined')
if (par[2] == None) or (par[2] == ''):
raise RuntimeError('Error: segment is limited')
if ((par[1] and par[2]) == None) or ((par[1] and par[2]) == ''):
raise RuntimeError('Error: segment undefined')
if (int(par[2]) >= length):
raise RuntimeError('Error: segment can not be greater than length the amount of lines')
if (par[1] == ''):
a = 0
if (par[2] == ''):
b = 0
segment = [int(par[1]), (int(par[2]) + 1)]
with open(par[0]) as f:
data = f.read().splitlines()
for k in range(segment[0], segment[1]):
print(data[k])
except (FileNotFoundError, IOError, NameError):
print('[!] Error: your input is incorrect. The file may be missing or something else. \n[?] For further information see full error logs: \n',sys.exc_info())
except RuntimeError as e:
print(e)
Problem:
When I try running my program in different ways to test each of my Runtime errors I always get this message:
Traceback (most recent call last):
File "C:\Users\1\Desktop\IT\pycharm\sem_2.py", line 10, in <module>
if (par[2] == None) or (par[2] == ''):
IndexError: list index out of range
I cannot wrap my head around how can I properly handle multiple Runtime errors so they would display as a text message. I haven't found any solution to my question anywhere online, so I'm trying to ask here.
I will appreciate any help, thanks in advance.
Your code would catch FileNotFoundError, IOError, NameError and RuntimeError but what is actually thrown is IndexError and that is not handled.
You may want to add IndexError it to the first except block:
except (FileNotFoundError, IOError, NameError, IndexError):
print('[!] Error: input incorrect!') # ^^^^^^^^^^^^
or perhaps add another except block if you want a custom message for IndexError:
except (FileNotFoundError, IOError, NameError):
print('[!] Error: input incorrect!')
except IndexError:
print('[!] Error: IndexError just happened!')
By the way, the following will always be False because the code in parentheses will resolve to a bool first, which can either be True or False and these are obviously never equal to '' or None:
((par[1] and par[2]) == None) or ((par[1] and par[2]) == '')
You may way want to rewrite it to:
(par[1] is None and par[2] is None) or (par[1] == '' and par[2] == '')

Python - try/except not working when variable assigned to sys.argv

I have this section in my code:
# I/O files
inp_arq = sys.argv[1]
out_arq = sys.argv[2]
pad_ref = "pad_ref03.fasta"
tes_mdl = "model_05_weights.best.hdf5"
and at the end:
try:
results_df.to_csv(out_arq,index = False)
print(f"File saved as: {out_arq}")
except IndexError:
print("No output file created")
If no file is passed in as out_arq (sys.argv[2]) it should run the script and print "No output file created" at the end. But I'm getting the "IndexError: list index out of range."
But if I comment out the "out_arq = sys.argv[2]" line and change the code to:
try:
results_df.to_csv(sys.argv[2],index = False)
print(f"File saved as: {sys.argv[2]}")
except IndexError:
print("No output file created")
It works and I got the message, but I'm not sure why. I'd like to have all my I/O file/vars at the begginig of the script, but with this one (out_arq) I can't.
How can I solve this? And why this happens?
If you look at the stack trace that is printed by the exception, you should see that the exception is raised on this line:
out_arq = sys.argv[2]
This is outside the try block, so the exception is not caught, and causes your program to terminate.
A solution is to check, before indexing the array, whether the element exists:
out_arq = sys.argv[2] if len(sys.argv) >= 3 else None
Then use if instead of try:
if out_arq:
results_df.to_csv(out_arq,index = False)
print(f"File saved as: {out_arq}")
else:
print("No output file created")

Error in try/except construction [duplicate]

This question already has an answer here:
Python try except else invalid syntax?
(1 answer)
Closed 6 years ago.
Im just sitting for 10 minutes staring at a simple piece of code, which I have copied from a guide and I can't understand why I am getting an error.
def transformation(x):
date_format = "%d/%m/%Y"
try:
a = dt.date(int(x[6:10]), int(x[3:5]), int(x[0:2]))
else:
a = dt.datetime.strptime(x, date_format)
finally:
return a
File "<ipython-input-91-f1f6fe70d542>", line 5
else:
^
SyntaxError: invalid syntax
Maybe this is just me... Whats wrong?
After adding except:
def transformation(x):
date_format = "%d/%m/%Y"
try:
a = dt.date(int(x[6:10]), int(x[3:5]), int(x[0:2]))
except pass
else:
a = dt.datetime.strptime(x, date_format)
finally:
return a
File "<ipython-input-93-c2285c857574>", line 5
except pass
^
SyntaxError: invalid syntax
You need an except clause to use else:
The try ... except statement has an optional else clause, which, when
present, must follow all except clauses
[Emphasis mine]
I just saw it from the python document page, so I'm just gonna quote what it says to you:
The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()

Run some code if any exception occur and to a specific exception

I have this function. My pygame's text to rectangle converter.
def text_to_rect(text, name='default'):
try:
font = load.text_style[name]['font']
aa = load.text_style[name]['aa']
color = load.text_style[name]['color']
except NameError:
font_path = pygame.font.get_default_font()
font = pygame.font.Font(font_path, 24)
aa = 1
color = (0,0,0)
if not name=='default':
text = text+'(ERROR: Global load object not defined.)'
except KeyError:
font_path = pygame.font.get_default_font()
font = pygame.font.Font(font_path, 24)
aa = 1
color = (0,0,0)
if not name=='default':
text = text+'(ERROR: '+name+' text style does not exist.)'
return font.render(text,aa,color)
In two except blocks there are 4 lines of the same code. I want to run these 4 lines if any exception occurs, then rest to a specific exception.
You can actually combine exceptions into one statement:
try:
#code that you expect errors from
except KeyError, NameError:
#exception code
except:
#Of course, you can also do a naked except to catch all
#exceptions,
#But if you're forced to do this, you're probably
#doing something wrong. This is bad coding style.
EDIT
For your case, if you want your code execution to depend on the error caught, do this:
try:
#Code to try
except (KeyError, NameError) as e:
#Code to execute in either case
if isinstance(e, KeyError):
#code to execute if error is KeyError
else:
#code to execute if error is NameError

Categories

Resources