12.4. Defining exceptions

Python provides a set of pre-defined exception classes that you can specialize by sub-classing to define specific exceptions for your application (Figure 12.1).

Go to

Since exceptions are defined as classes and by inheritance, you will need some knowledge about classes in order to fully understand this section (see Chapter 18).

Example 12.4. Raising your own exception in case of a wrong DNA character

In the following code, you define an exception AlphabetError that can be used when the sequence passed to the function does not correspond to the alphabet.

class AlphabetError(ValueError):                                          (1)

def check_dna(dna, alphabet='atgc'):
    """ using exceptions """
    for base in dna:
        if base not in alphabet:
            raise AlphabetError, "%s not in %s" % (base, alphabet)

    return 1

Definition of a new exception in category ValueError: AlphabetError is a class, that is a sub-class of class ValueError. The only statement present in class AlphabetError is pass since AlphabetError does not define any new behaviour: it is just a new class name.

Example 12.5. Exceptions defined in Biopython

Some Biopython modules define their own exceptions, such as:

  • ParserFailureError (GenBank package)
  • BadMatrix (SubsMat package)