Logo

How to catch multiple exceptions in one line in Python? (in the "except" block)

Catching Multiple Exceptions Gracefully in a Single except Clause

In Python, you can elegantly handle multiple exceptions using a single except block by grouping the exception types into a tuple. This approach keeps your code concise and clear, especially when the same recovery or logging logic applies to multiple errors. Instead of writing separate except clauses for each exception type, you can combine them, making your code more maintainable and readable.

Basic Syntax:

try: # Code that may raise multiple types of exceptions result = int("not_an_integer") except (ValueError, TypeError) as e: print(f"An error occurred: {e}")

In this snippet, if the code inside the try block raises either a ValueError or a TypeError, Python will catch it in one except clause. The variable e will be bound to the exception instance, allowing you to inspect the error message, log it, or take any appropriate action.

Key Points:

  • Order Matters for Multiple Except Blocks: If you have multiple except blocks, Python will try them in order. Specific exceptions should generally come before more general exceptions to avoid “shadowing” more granular error handling.
  • Combining Exceptions Logically: Group exceptions together only if you want to handle them the same way. This keeps the code meaningful. If a ValueError and a TypeError both call for the same recovery action, combining them into one clause makes sense.
  • No Limit to the Number of Exceptions: You can include as many exception types as you need within the tuple, as long as they’re comma-separated.

Example with Logging:

import logging try: data = int("some_string") except (ValueError, TypeError) as error: logging.error("Failed to convert data: %s", error) # Additional recovery logic here

Here, both ValueError and TypeError trigger the same response—logging the error and executing the same recovery steps—so grouping them makes the code cleaner.

Strengthen Your Python Skills: Mastering exception handling is part of becoming a proficient Python developer. If you’re just starting out or need a stronger foundation:

  • Grokking Python Fundamentals: Ideal for beginners, this course ensures you understand core Python concepts, including exception handling best practices.

For those aiming to excel in technical interviews and algorithmic challenges:

You can also watch videos on the DesignGurus.io YouTube channel for additional tips, insights, and step-by-step guides on various coding and system design topics.

In Summary: Catching multiple exceptions in one line is as simple as grouping them in a tuple within a single except clause. This approach makes your code neater, reduces repetition, and improves maintainability—essential attributes for writing clean, professional-quality Python code.

TAGS
Python
CONTRIBUTOR
TechGrind