try ... except blocks
Use the try keyword with a colon and some code with the idea that python needs to see if it fails or generates an error. If it does fail you need to have the except keyword with a colon to catch or trap that error or failure.
try:
print(football)
except:
print("An exception occurred")
print(football)
except:
print("An exception occurred")
Optionally you can use an else: with a colon if the try block finishes cleanly without error or failure and also optionally a finally: block which executes regardless of whether the try block's code fails or succeeds, with or without error. The finally block is good for closing files or cleaning up your variable space.
football = "inflated"
try:
print(football)
except:
print("An exception occurred")
print(football)
except:
print("An exception occurred")
else:
print("Caught for a touchdown!")
finally:
print("score may have changed")
You can use a series of excepts, one for each type of error.
else will only execute if something went wrong and it must be written after all the except calls. There can only be one else for each try.
football = "inflated"
try:
print(football)
except:
print("A name exception occurred")
print(football)
except:
print("A name exception occurred")
except:
print("A type exception occurred")
print("A type exception occurred")
else:
print("Caught for a touchdown!")
finally:
print("score unchanged")
You can force/throw an exception - a programmer induced error or failure - with the raise keyword with no colon. raise needs an argument which is an object of general type of the built-in Exception class and its behavior will be like a real error to the terminal rather than a forced one by the programmer; the two will look the same other than the customized text message, if any (the Exception object can be devoid of any arguments in its parentheses).
time_on_clock = 5
if time_on_clock == 0
raise Exception("Game over.")
else:
print("Keep playing")
# result is
Keep Playing
another example:
try:
print(score)
except:
raise Exception()
# result is:
NameError: name 'score' is not defined. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./yourscript", line 123, in Exception
Note there are 2 errors, one naturally occurring from Python and the other forced by the programmer.
You can also raise more specific error types such as TypeError or NameError. See this URL for a complete list of python errors:
When the programmer uses a raise keyword, no code will be executed after the raise command is complete.
No comments:
Post a Comment