Handling exceptions passed from MySQL
MySQL for Python takes care of the nitty-gritty of communication between your program and MySQL. As a result, handling exceptions passed from MySQL is as straightforward as handling exceptions passed from any other Python module.
Python exception-handling
Python error-handling uses a try...except...else
code structure to handle exceptions. It then uses raise
to generate the error.
while True: try: x = int(raw_input("Please enter a number: ")) break except: print "That is not a valid number. Please try again..."
While this is the textbook example for raising an error, there are a few points to keep in mind.
while True:
This sets up a loop with a condition that applies as long as there are no exceptions raised.
try...break
Python then tries to execute whatever follows. If successful, the program terminates with break. If not, an exception is registered, but not raised.
except
The use of except
tells Python what to do in the...