Handling Errors

(Sponsors) Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!

Interacting with a database is an error prone process, so we must always implement some mechanism to handle errors gracefully.

MySQLdb has MySQLdb.Error  exception, a top level exception that can be used to catch all database exception raised by MySQLdb module.

Two main error in MySQLdb

There are two categories of exception class in MySQLdb you need to be aware:

  1. DatabaseError.
  2. InterfaceError.

DatabaseError: This exception raises when there is problem in data processing, error in sql syntax, mysql internal problems. If a connection is made and a problem arises then DatabaseError will catch it. There are 6 types of DatabaseError:

  1. DataError.
  2. InternalError.
  3. IntegrityError.
  4. OperationalError.
  5. NotSupportedError.
  6. ProgrammingError.

DataError: MySQLdb throws this error when there is problem in the data processing, like division by zero, numeric value of of range.

InternalError: This exception is raised when there is some internal error in MySQL database itself. For e.g invalid cursor, transaction out of sync etc.

IntegrityError: This exception is raised when foreign key check fails.

OperationalError: This exception is raised for things that are not in control of the programmer. For e.g unexpected disconnect, error in memory allocation etc, selected database not exists.

NotSupportedError: This exception is raised when there is method or api that is not supported.

ProgrammingError: This exception is raised of programming errors. For e.g table not found, error in mysql syntax, wrong number of parameters specified etc.

InterfaceError: When database connection fails for some reason, MySQLdb will raise an InterfaceError. Note InterfaceError only get raise when there is internal problem in connection to the database, MySQLdb will not raise InterfaceError because of wrong database name or password.


Other Tutorials (Sponsors)

This site generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!

Leave a Reply

Your email address will not be published. Required fields are marked *