O'Reilly logo

Data Structures and Algorithms Using Python by Rance D. Necaise

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Appendix C. Exceptions

Unforeseen errors can occur in a program during run time due to faulty code or invalid input. Consider the following sample code segment, which attempts to access a non-existent element of a list:

myList = [ 12, 50, 5, 17 ]
print myList[ 4 ]

When this code is executed, the program aborts and the following message is displayed:

Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
IndexError: list index out of range

The last line in the message provides information as to the type of run-time error that caused the program to abort. In this case, there are only four elements in the list numbered 0, 1;2, 3 and thus subscript 4 is out of range.

Python, like many other high-level programming languages, raises an exception when an error occurs. An exception is an event that can be triggered and optionally handled during program execution. When an exception is raised indicating an error, the program can contain code to catch the exception and gracefully handle it. When an exception is not handled, the program will abort as was the case in our example above.

Catching Exceptions

Consider the following example in which we want to extract an integer value from the user with the input() function:

value = int( input("Enter an integer value: ") )

What happens if the user entered 4x at the prompt instead of an actual numeric value? Python raises an exception which causes the program to abort with the following message printed to the terminal.

Traceback (most recent ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required