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 ...

Get MySQL for Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.