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.
🛡️ 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.
More Topics
- How to Pass Command Line Arguments to Your Python Script
- Solving the Classic FizzBuzz Problem in Python: A Step-by-Step Tutorial
- How to Solve the Pythagorean Theorem with a Python Script
- What’s the Difference Between Syntax, Runtime, and Logic Errors in Python?
- What Are Dictionaries in Python and How Do You Use Them?
- Thinking Recursively: A Beginner’s Introduction to Recursion in Python
- How to Read and Write Files in Python