Skip to content

Python Course – 7. Exceptions

Learn how Python exceptions work: how to catch them, which ones to handle and which to let through, with video lessons, theory and hands-on exercises.

In programming, there are no errors as such; there are only exceptions. The typical error window is simply an exception that gets caught and shown to the user. The program failed because there was an exception that wasn’t handled, so the operating system had to handle it.

Theory

Skip to PDF content

7.1- Exceptions

A program can raise many exceptions. The key is knowing how to handle them, having ways to locate them, and knowing which ones we have to handle and which ones we should let through.

Exercises

Exercise 7.1-frutas.py

Create a list with five fruits.

Ask the user on screen for an index of the list and return the item at that index. If it raises an exception, you’ll have to catch it and tell the user about the error.

Console capture of the fruit exercise: returns 'manzana' and 'plátano' and warns of an error when asking for position 99

Exercise 7.2-contador_limitado.py

Create a while True loop that is always iterating and adding +1 to a counter (and print it).

The computer where we run this is a bit limited, and the counter can’t go above 9999. At that point, a BufferError exception will be raised with the message “Se ha superado los 9999 registros”, since nothing more can be added. If you run it with this code (as it is now, without going any further in the exercise), the program will end with a runtime error.

Console capture of the counter reaching 9999 and the BufferError traceback 'Se ha superado los 9999 registros'

But we don’t want the program to end; we want it to keep going after the loop. To do that, we’ll catch the exception outside the loop, which is where we’ll show the error message in the following format: “Se ha detectado el error ‘{mensaje_del_buffererror}'”

 And to finish, outside the loop we’ll print the text: “el código continua”

Console capture of the counter and the caught error with try/except; the program goes on printing 'el código continua'

“Python Course – 7. Exceptions” by Ramón Invarato at jarroba.com, licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0. Registered at Safe Creative.

Ramón Invarato

I design and build data platforms and intelligent systems, and I enjoy sharing that experience here.

You may also like

Exceptions in Java, with Examples

Learn what exceptions are in Java, how the Throwable hierarchy works, and how to handle errors with try - catch - finally, with simple, practical examples.

Oct 12, 2014

Comments

Leave a comment


This site uses Akismet to reduce spam. Learn how your comment data is processed.