What happens when your program encounters an error, like a user entering text instead of a number, or trying to open a file that doesn’t exist? By default, Python will crash. To prevent this and handle problems gracefully, you can use a powerful feature called exception handling, using try
and except
blocks.
Table of Contents
🛡️ The Try Block: Protecting Your Code
Any code that you suspect might cause an error (an “exception”) should be placed inside a try
block. Python will attempt to execute this code as usual. If everything runs without any issues, the program continues normally after the `try` block, and any associated `except` blocks are skipped.
🚨 The Except Block: Catching the Error
If an exception *does* occur inside the `try` block, Python immediately stops executing the rest of the code in that block and jumps to the corresponding except
block. This block contains the code that will run to handle the error. You can specify which type of exception you want to catch, like FileNotFoundError
or ValueError
. This allows you to display a friendly error message, prompt the user to try again, or take other recovery actions instead of just crashing.try:
inf = open("myfile.txt", "r")
except FileNotFoundError:
print("Sorry, that file could not be found.")
✅ Why is Exception Handling So Important?
Using try...except
makes your programs more robust and user-friendly. Instead of seeing a scary traceback message, the user gets a clear explanation of what went wrong. It gives you, the programmer, control over how your program behaves in unexpected situations. You can use it to validate user input, handle network issues, or manage file access problems, ensuring your application can recover from errors without stopping completely.
Learning to anticipate and handle exceptions is a key characteristic of writing professional, high-quality Python code.
—
Stephenson, Ben. The Python Workbook: A Brief Introduction with Exercises and Solutions. 3rd ed., Springer, 2025.
- Python Coding Essentials: Reliability by Abstraction
- Python Coding Essentials: Different Types of Data
- Python Coding Essentials: Embrace Storage and Persistence
- Python Coding Essentials: Neater Code with Modules
- Python Coding Essentials: Lock Down with Data Encryption
- Python Coding Essentials: Files and Modules Done Quickly
- Python’s Itertools Module – How to Loop More Efficiently