
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Catch Multiple Exceptions in One Line Except Block in Python
In Python, instead of writing separate except blocks for each exception, you can handle multiple exceptions together in a single except block by specifying them as a tuple.
In this example, we are catching both ValueError and TypeError using a single except block -
try: x = int("abc") # Raises ValueError y = x + "5" # Would raise TypeError if above line did not error except (ValueError, TypeError) as e: print("Caught an exception:", e)
The above program will generate the following error -
Caught an exception: invalid literal for int() with base 10: 'abc'
Need to Handle Multiple Exceptions in one except?
You can avoid repeating the same code (duplicacy) for different errors by putting multiple exceptions in a single except block. It keeps your error handling simple and organized when you want to do the same thing for different types of errors.
Example: Handling file-related errors together
In this example, we handle both FileNotFoundError and PermissionError together as they require the same response -
try: with open("file.txt") as f: data = f.read() except (FileNotFoundError, PermissionError): print("Cannot open the file due to missing file or permissions. Creating the file now.") with open("file.txt", "w") as f: f.write("") # create an empty file
Following is the output obtained if the file is missing or permission is denied -
Cannot open the file due to missing file or permissions. Creating the file now.
Accessing the exception Object
When catching multiple exceptions, you can assign the exception instance to a variable using the as keyword. This allows you to inspect or log the error message.
Example: Printing the exception Message
In this example, the exception object is captured and printed -
try: num = int("xyz") except (ValueError, TypeError) as error: print("Error occurred:", error)
The output is -
Error occurred: invalid literal for int() with base 10: 'xyz'
When not to catch Multiple Exceptions together
Sometimes, different exceptions need different handling. In such cases, we need to use separate except blocks instead of grouping them.
Example: Separate except Blocks
In this example, we handle ValueError and TypeError differently -
try: x = int("abc") y = x + "5" except ValueError: print("ValueError: Invalid conversion.") except TypeError: print("TypeError: Unsupported operation.")
The output is -
ValueError: Invalid conversion.