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 content7.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.

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.

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”

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

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.
Advanced Dockerfile: Multi-Stage Builds, Registries, and Tricks
Free Docker course. Expert Docker tricks: multi-stage builds, optimizing images, faster build times, and distributing images through Docker registries.


Leave a comment