
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to catch multiple exceptions in one line (except block) in Python?
We catch multiple exceptions in one except block as follows
An except clause may name multiple exceptions as a parenthesized tuple, for example
try: raise_certain_errors(): except (CertainError1, CertainError2,…) as e: handle_error()
Separating the exception from the variable with a comma still works in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now we should use ‘as’.
The parentheses are necessary as the commas are used to assign the error objects to names. The ‘as’ keyword is for the assignment. We can use any name for the error object like ‘error’, ‘e’, or ‘err’
Given code can be written as follows
try: #do something except (someException, someotherException) as err: #handle_exception()
- Related Articles
- How to raise an exception in one except block and catch it in a later except block in Python?
- Is it possible to catch multiple Java exceptions in single catch block?
- How to use the ‘except’ clause with multiple exceptions in Python?
- How can I write a try/except block that catches all Python exceptions?
- How to catch exceptions in JavaScript?
- Is it possible to have multiple try blocks with only one catch block in java?
- How to use the ‘except clause’ with No Exceptions in Python?
- How to catch all the exceptions in C++?
- Can a try block have multiple catch blocks in Java?
- How to display multiple labels in one line with Python Tkinter?
- How to input multiple values from user in one line in Python?
- How to catch all JavaScript unhandled exceptions?
- Can we define a try block with multiple catch blocks in Java?
- How to catch many exceptions at the same time in Kotlin?
- Can we declare a try catch block within another try catch block in Java?

Advertisements