Basic Python Exception Handling

Last modified: 
Sunday, March 29th, 2015
Topics: 
Python

The basics of exception handling in the Python programming language. Tested in Python 2.7.1+.

Raising Exceptions with Raise

Here we raise an unamed exception for the heck of it with the raise clause.

raise Exception # This will output a generic **Exception** error.

Here we raise an exception with a custom error message.

# Exception: this is a custom error message
raise Exception('this is a custom error message') 

Division By Zero with No Exception Handling

This code has no exception handling. Entering 0 for
the denomitator will cause a division by zero error.

x = input('Enter the numerator: ')
y = input('Enter the denominator: ') 
# If y = 0, ZeroDivisionError: integer division or modulo by zero
print x/y

Capturing Division By Zero Error

This code will catch zero division errors and display a message.
However if x or y is not an integer, it will throw a Name error:
NameError: name 'foo' is not defined.

try:
    x = input('Enter the numerator: ')
    y = input('Enter the denominator: ')
    print x/y
except ZeroDivisionError:
    # If y = 0, catch the exception and display a message.
    print 'Denominator may not be zero!'

Handling Different Types of Exceptions Individually

This code will display a message for division by zero input errors
and another message for Name Errors resulting from passing a string
or character through input().

try:
    x = input('Enter the numerator: ')
    y = input('Enter the denominator: ')
    print x/y
except ZeroDivisionError:
    print 'Denominator may not be zero!'
except NameError:
    print 'Input must be an integer!'

Handling Different Types of Exceptions as a Group

This code displays a single message for Zero Division errors and Name errors.

try:
    x = input('Enter the numerator: ')
    y = input('Enter the denominator: ')
    print x/y
except (ZeroDivisionError, NameError):
    print 'Please check that your input is an integer and you are not dividing by zero!'

Catching the Exception Object

This code captures the Exception using the second argument "e" and prints it to the screen.
This example, and those above, will throw the following uncaught exception if the return
key is pressed with no input: SyntaxError: unexpected EOF while parsing.

try:
    x = input('Enter the numerator: ')
    y = input('Enter the denominator: ')
    print x/y
except (ZeroDivisionError, NameError), e:
    print e

Catching All Exceptions and Using Else

Here we catch all exceptions using the parent Exception class.

try:
    x = input('Enter the numerator: ')
    y = input('Enter the denominator: ')
    print x/y
except Exception, e:
    print e
else:
    #This message will be displayed only if the try statement passes.
    print 'Beware: This program does not work as expected with floating point numbers!'

Blindly Catching All Exceptions

This code will catch all excpetions, print out a generic message, and start the program over.
One bad thing about this approach is that the unconsidered exception handling prevents the
user from killing the application with ctrl+c!

while True:
    try:
        x = input('Enter the numerator: ')
        y = input('Enter the denominator: ')
        print x/y
    except:
        print 'Integers only. Please try again!'
    else:
        break

Finally Clause Always Runs

This code is as above with the addition of a finally clause. Statements in a finally clause will always be run -- whether or not there was an exception and regardless of any else clauses.

while True:
    try:
        x = input('Enter the numerator: ')
        y = input('Enter the denominator: ')
        print x/y
    except:
        print 'Integers only. Please try again!'
    else:
        break
    finally:
        print 'This line prints regardless of whether or not we have caught '
        print 'any exceptions and even though the else clause calls a break.'

References

These examples of catching exceptions were inspired by Beginning Python from Novice to Professional by Magnus Lie Hetland.


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.