i'm stuck with my simple code, i'm a newbie for coding.. I'm using python and
In my list i have bad values that made exceptions (httperror : 404) . I want to ignore this exceptions and continue my loop. But with my code, the print("Http error") loop again and again. I don't know how to pass this exception to loop the entire code again.
while i < len(list_siret):
try :
data = api.siret(list_sirets[i]).get()
str_datajs = json.dumps(data, indent= 4)
a_json = json.loads(str_datajs)
i +=1
print("test1", i ,str_datajs)
except urllib.error.URLError :
print("Http error")
pass
Since you have print("Http error") inside the except block, it will be executed every time the exception occurs.
Consider the more idiomatic approach below:
for siret in list_siret:
try:
data = api.siret(siret).get()
except urllib.error.URLError:
continue
str_datajs = json.dumps(data, indent=4)
a_json = json.loads(str_datajs)
print("test1", i ,str_datajs)
We iterate directly over list_siret without needing to index into it and manually manage i, and instead of passing we just move to the next element in the list in case an exception was raised.
Related
I am making a Reddit bot using PRAW and the code gives me the error that the exception is not iterable. Here is a simplification of my code:
try:
#something with praw that isn't relevant
except Exception as e: #this except error catches the APIexception, APIexpections in PRAW are a wide field of exceptions that dont't always have the same solution, so I scan the text for the error I'm looking for.
print(e)
if "keyword thats in the error" in e:
#fix the problem with the specific error
else:
print("Unkown APIExpection error")
This works fine for me, but when I run this code:
try:
#something
except Exception as e:
for character in e:
print(character)
#I also tried this
try:
#something
except Exception as e:
for character in str(e):
print(character)
#None of the above work but this is my actual code and what I need to do, anything that gets the above to work should work here too, I'm just letting you know this so that I don't get any other errors I have to ask another question for.
try:
#something
except Exception as e:
characterNum = 0
for character in e:
characterNum += 1
print(str(characterNum) + ": " + character)
It gives me a "TypeError: 'RedditAPIException' is not iterable", RedditAPIException can be ignore though as that's just the error I'm catching.
Convert the exception to string and then check in the if statement.
Change to => if "keyword thats in the error" in str(e):
Hi I have a function that parses the first 60 lines in a file and is supposed to alert a user if there are lines that are entirely whitespace. However these can occur anywhere in those 60 lines so I want the script to parse the entire 60 lines mainly because I need data from a couple of the lines for my error reporting. And we might want to know where those errors occur in the future. I wrote this:
def header_data(data):
dictionary = {}
datalen = len(data)
itrcntr = 0
try:
for line in data:
itrcntr += 1
if line.isspace():
raise Exception('File has badly formatted header data line(s)')
else:
linesplit = line.rstrip().split(":")
if len(linesplit) > 1:
dictionary[linesplit[0]] = linesplit[1].strip()
return dictionary
except Exception as e:
errmsg = str(e)
if itrcntr == datalen:
return (dictionary, errmsg)
else:
pass
With this function, I'd expect if it sees that itrcntr is not equal datalen, it would pass and go back to the try block and move on to the next line. But this doesn't happen. INstead it breaks out of the function and continues in the next line in the function caller. How can I make it continue looping till it reaches to the end of the loop in which it will then return the dictionary along with the error message? Or can this not be done with try catch exception handlers?
Unless you want to catch exceptions other than the situation of line.isspace, I wouldn't use a try block at all. Just collect your errors in a list, eg:
errors = []
for line in data:
itrcntr += 1
if line.isspace():
errors.append('File has badly formatted header data at line %d.' % itrcntr)
# then at the end:
if errors:
# do something about it...
If any exception occurred, try clause will be skipped and except clause
will run.
If you raise an exception anywhere in the Try, everything else will be skipped. So if you want the loop to continue, then just don't use Try Except.
Just collect every error message and then return it.
I'm a Python learner, trying to handle a few scenarios:
Reading a file.
Formatting Data.
Manipulating/Copying Data.
Writing a file.
So far, I have:
try:
# Do all
except Exception as err1:
print err1
#File Reading error/ File Not Present
except Exception as err2:
print err2
# Data Format is incorrect
except Exception as err3:
print err3
# Copying Issue
except Exception as err4:
print err4
# Permission denied for writing
The idea of implementing in this fashion is to catch the exact error for all different scenarios. I can do it in all separate try/except blocks.
Is this possible? And reasonable?
Your try blocks should be as minimal as possible, so
try:
# do all
except Exception:
pass
is not something you want to do.
The code in your example won't work as you expect it to, because in every except block you are catching the most general exception type Exception. In fact, only the first except block will ever be executed.
What you want to be doing is having multiple try/except blocks, each one responsible for as few things as possible and catching the most specific exception.
For example:
try:
# opening the file
except FileNotFoundException:
print('File does not exist')
exit()
try:
# writing to file
except PermissionError:
print('You do not have permission to write to this file')
exit()
However, sometimes it is appropriate to catch different types of exceptions, in the same except block or in several blocks.
try:
ssh.connect()
except (ConnectionRefused, TimeoutError):
pass
or
try:
ssh.connect()
except ConnectionRefused:
pass
except TimeoutError:
pass
As DeepSpace stated,
Your try blocks should be as minimal as possible.
If you want to achieve
try:
# do all
except Exception:
pass
Then you might as well do something like
def open_file(file):
retval = False
try:
# opening the file succesful?
retval = True
except FileNotFoundException:
print('File does not exist')
except PermissionError:
print('You have no permission.')
return retval
def crunch_file(file):
retval = False
try:
# conversion or whatever logical operation with your file?
retval = True
except ValueError:
print('Probably wrong data type?')
return retval
if __name__ == "__main__":
if open_file(file1):
open(file1)
if open_file(file2) and crunch_file(file2):
print('opened and crunched')
Yes this is possible.
Just say as example:
try:
...
except RuntimeError:
print err1
except NameError:
print err2
...
Just define the exact Error you want to intercept.
I have a python selenium script that runs through a loop like this...
for i, refcode in enumerate(refcode_list):
try:
source_checkrefcode()
except TimeoutException:
pass
csvWriter.writerow([refcode, 'error', timestamp])
If there is a problem during the source_checkrefcode then the script crashes with an error.
How can I add error handling to this loop so that it just moves to the next item instead of crashing?
You can add a check over exception message, below is the sample code for your understanding.
for i, refcode in enumerate(refcode_list):
try:
source_checkrefcode()
except Exception as e:
if 'particular message' in str(e):
# Do the following
# if you don't want to stop for loop then just continue
continue
I agree with Hassan's Answer. But if you use continue then you won't process any other block of code.
for i, refcode in enumerate(refcode_list):
try:
source_checkrefcode()
except Exception as e:
if 'particular message' in str(e):
# Do the following
# if you don't want to stop for loop then just continue
continue
# another code of block will skip. Use pass or continue as per your requirement.
You must understand the difference between pass and continue
Link
I am trying in Python.
try:
newbutton['roundcornerradius'] = buttondata['roundcornerradius']
buttons.append(newbutton)
buttons is a list. roundcornerradius is optional in buttondata.
Alas this gives
buttons.append(newbutton)
^ SyntaxError: invalid syntax
I just want to ignore the cases where roundcornerradius does not exist. I don't need any error reported.
why arent you using the except keyword
try:
newbutton['roundcornerradius'] = buttondata['roundcornerradius']
buttons.append(newbutton)
except:
pass
this will try the first part and if an error is thrown it will do the except part
you can also add the disered error you want to except a certain error like this
except AttributeError:
you can also get the excepted error by doing this:
except Exception,e: print str(e)
You should catch a try with exception:
try:
code may through exception
except (DesiredException):
in case of exception
Also you can use else with try if you need to populate new buttons only when try succeeds:
try:
newbutton['roundcornerradius'] = buttondata['roundcornerradius']
except KeyError:
pass
else:
buttons.append(newbutton)
single except: with no exception class defined will catch every exception raised which may not be desired in some cases.
Most probably you will get KeyError on your code but I am not sure.
See here for builtin exceptions:
http://docs.python.org/2/library/exceptions.html
You must close block with except or finally if using try.
try:
newbutton['roundcornerradius'] = buttondata['roundcornerradius']
except KeyError:
pass#omit raise if key 'roundcornerradius' does not exists
buttons.append(newbutton)
If you know default value for 'roundcornerradius' - you dont need no try ... except
newbutton['roundcornerradius'] = buttondata.get('roundcornerradius', DEFAULT_RADIUS)
buttons.append(newbutton)