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
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):
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.
I have this code using a While True with a try catch. The final else statement is always being executed when the 'try' is successful and I'd like to understand why - I think I'm not understanding the program flow correctly.
while True:
try:
subprocess.call(["wget", "-O", "splunk-8.0.1-6db836e2fb9e-Linux-x86_64.tgz", "https://www.splunk.com/bin/splunk/DownloadActivityServlet?architecture=x86_64&platform=linux&version=8.0.1&product=splunk&filename=splunk-8.0.1-6db836e2fb9e-Linux-x86_64.tgz&wget=true"])
print("successfully downloaded splunk enterprise")
time.sleep(2)
except OSError as e:
if e.errno == 2:
print(e)
print("wget doesn't seem to be installed")
time.sleep(2)
print("attempting to install wget")
time.sleep(2)
subprocess.call(["yum", "install", "wget"])
else:
print(e)
print("unknown error response, exiting...")
break
else:
print("something else went wrong while trying to download splunk")
break
based on python documentation, try-except can take an optional else statement:
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.
so based on this, your else statement will run if codes in try doesn't raise any exception!
what you want is another except clause that catches a general exceptation, so you just need to replace else with except:
while True:
try:
subprocess.call(["wget", "-O", "splunk-8.0.1-6db836e2fb9e-Linux-x86_64.tgz", "https://www.splunk.com/bin/splunk/DownloadActivityServlet?architecture=x86_64&platform=linux&version=8.0.1&product=splunk&filename=splunk-8.0.1-6db836e2fb9e-Linux-x86_64.tgz&wget=true"])
print("successfully downloaded splunk enterprise")
time.sleep(2)
except OSError as e:
if e.errno == 2:
print(e)
print("wget doesn't seem to be installed")
time.sleep(2)
print("attempting to install wget")
time.sleep(2)
subprocess.call(["yum", "install", "wget"])
else:
print(e)
print("unknown error response, exiting...")
break
except:
print("something else went wrong while trying to download splunk")
break
The else clause of a try executes if the code inside the try did not throw an exception. If you want to catch any exception, use except without specifying an exception class:
except:
print("something else went wrong while trying to download splunk")
break
However, consider just omitting this piece of code. As it is currently written, it doesn't tell you what went wrong. If you remove these lines, you will get an error message that tells you what happened and on which line the error occurred.
From here:
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.
So the else clause will run if the code within the try block runs successfully.
I have this try block in my code :
try:
installation('isc-dhcp-server')
except:
print('Oops an error...')
sys.exit(8)
Here in a try/except block the sys.exit(8) will just exit this block and keep an error with code "8". This is just what I want. Now I want to use this except somehere else in a code to avoid somes parts link to this setup. How can I do that ?
I try to put the error in a variable with :
except Exception as NameofError:
And use NameofError with a if statement but this var is not defined in the local space (I think) so I can't use it.
Just initiate a variable before the try-catch block and assign the exception to it
caught_error = None
try:
# some error throwing func
except Exception as e:
caught_error = e
# your error handling code
print(caught_error)
Edit: However, if you still have sys.exit() in your catch block you probably won't have the chance to do anything to the exception given that your program will be terminated already.
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)