
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
Use Except Clause with Multiple Exceptions in Python
Using "except" Clause with Multiple Exceptions
It is possible to define multiple exceptions with the same except clause. It means that if the Python interpreter finds a matching exception, then it will execute the code written under the except clause.
Syntax
In general, the syntax for multiple exceptions is as follows -
Except(Exception1, Exception2,?ExceptionN) as e:
When we define the except clause in this way, we expect the same code to throw different exceptions. Also, we want to take action in each case.
Example
In this example, we are trying to add an integer and a string, which is not allowed in Python. This raises a TypeError.
Since the TypeError is one of the exceptions listed in the except clause, the program handles it and prints the exception details using sys.exc_info() -
import sys try: d = 8 d = d + '5' except(TypeError, SyntaxError)as e: print (sys.exc_info())
We get output as shown below -
(<class 'TypeError'>, TypeError("unsupported operand type(s) for +: 'int' and 'str'"), <traceback object at 0x7f5fb8d164c0>)
Advertisements