I’m curious what is the ‘proper’ pythonic way of handling this error with a while loop. I could simply check the string to see if it has a [-1] character beforehand in this example, but the actual code this example of my problem is based on is much more complicated.
try:
while mystring[-1] == '!' #Will throw an error if mystring is a blank string
print("Exclamation!")
mystring = mystring[:-1]
return mystring
except:
return ""
Effectively my problem is that my while loop is contingent on a check that, occasionally after some processing within the loop, will throw an error. The above is just a (perhaps overly) simplified illustration of that problem. I fixed it with a series of try: excepts:’s, but I feel like that’s not the “correct” way to be addressing this issue.
Two things your current code does that you shouldn’t do:
If you find yourself using while loops a lot in python, it suggests that you aren’t making the most effective use of python. Given python’s toolset you should almost always be using some sort of for loop. Without seeing a real sample of your code, I can’t say whether that’s actually true. If you want help in that area, post some code at http://codereview.stackexchange.com
A general solution to this problem is to write a function which handles the exception and use that.
In fact, in many cases already have exception-less equivalents to the standard constructs. This loop can easily be written using the .endswith() method. By using those or crafting your own you can deal with the exceptions most cleanly.