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:

Python
>>> 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 tryexcept blocks to manage errors gracefully
  • Specifying different except blocks for handling multiple types of exceptions separately
  • Using except to log error messages or perform cleanup actions when an error occurs
  • Providing user-friendly error messages or fallback solutions when an exception is raised

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.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 6, 2025 • Reviewed by Dan Bader