except
In Python, the except keyword catches and handles exceptions that occur during the execution of a program. It allows you to define a block of code that will run if an error or exception is raised in a preceding try block. The except keyword is essential for building robust programs that can gracefully handle unexpected situations and errors.
Python except Keyword Examples
Here’s an example to demonstrate how to use the except keyword:
>>> try:
... result = 10 / 0
... except ZeroDivisionError:
... print("You can't divide by zero!")
...
You can't divide by zero!
In this example, the code attempts to divide 10 by 0, which raises a ZeroDivisionError exception. The except block catches this exception and prints a friendly error message.
Python except Keyword Use Cases
- Catching and handling exceptions in
try…exceptblocks to manage errors gracefully - Specifying different
exceptblocks for handling multiple types of exceptions separately - Using
exceptto log error messages or perform cleanup actions when an error occurs - Providing user-friendly error messages or fallback solutions when an exception is raised
- Using
except*to handle exception groups raised by concurrent code (Python 3.11+)
Python except* for Exception Groups
Python 3.11 introduced the except* clause through PEP 654. Unlike a regular except clause, except* is designed to handle a BaseExceptionGroup, which can bundle several unrelated exceptions raised together. This is especially relevant when working with concurrent code that may surface multiple errors at once.
When you use except*, Python matches the exception group against the type you specify and runs your handler for the matching subset, while letting any non-matching exceptions propagate as a new group:
>>> try:
... raise ExceptionGroup("multiple errors", [ValueError("bad value"), TypeError("bad type")])
... except* ValueError as eg:
... print(f"Caught {len(eg.exceptions)} ValueError(s)")
... except* TypeError as eg:
... print(f"Caught {len(eg.exceptions)} TypeError(s)")
...
Caught 1 ValueError(s)
Caught 1 TypeError(s)
Here, each except* block handles only the exceptions in the group that match its type. Both blocks can run for the same try, which sets except* apart from the traditional except clause.
Related Resources
Tutorial
Python Exceptions: An Introduction
In this beginner tutorial, you'll learn what exceptions are good for in Python. You'll see how to raise exceptions and how to handle them with try ... except blocks.
For additional information on related topics, take a look at the following resources:
- Python's Built-in Exceptions: A Walkthrough With Examples (Tutorial)
- Python 3.11 Preview: Task and Exception Groups (Tutorial)
- Understanding the Python Traceback (Tutorial)
- Python's raise: Effectively Raising Exceptions in Your Code (Tutorial)
- Raising and Handling Python Exceptions (Course)
- Introduction to Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)
- Working With Python's Built-in Exceptions (Course)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)
- Getting the Most Out of a Python Traceback (Course)
- Using raise for Effective Exceptions (Course)
- Python's raise: Effectively Raising Exceptions in Your Code (Quiz)