In this Python tutorial, we will learn Python catch multiple exceptions and also we will cover these topics:
- Python catching exceptions
- Python catch different exception types
- Python catch multiple exceptions in one line
- Python catch-all exceptions
- Python handle different exception types
- Catch multiple exceptions python3
- User-defined exceptions in python
- Customized Excepting classes
Python catch multiple exceptions
Now, we can see catch multiple exceptions in python.
- In this example, I have imported a module called math and declared a variable as integers, and assigned it as integers =[‘orange’,6,-8’apple’].
- The for loop is used for iteration and try is used. The try statement allows defining a block of code that tests the error while it is being executed.
- If any error occurs try will be skipped and except will execute. Here the error was ‘orange’ so the except executed as “The input is not supported“.
- Another input is -8 which was a negative number again except is executed as a number is not a positive integer and the error message is displayed.
Example:
import math
integers = ['orange',6,-8,'apple']
for number in integers:
try:
number_factorial = math.factorial(number)
except TypeError:
print("The input is not supported.")
except ValueError:
print( number," is not a positive integer.")
In the below screenshot, we can see the error message as the output:
You may also like Python Exceptions Handling and Python concatenate list with examples.
Python catching exceptions
Now, we can see catching exceptions in python.
- In this example, I have imported a module called sys and random and declared a variable as numberlist and assigned numberlist = [‘a’, 2, 2].
- The for loop is used for iteration and try block is used as the first number from the list is not an integer an error occurred.
- So except is executed as next entry and also it gives ValueError.
- The second number is taken and the addition operation performed and the result is displayed.
- The sys.exc_info is used to obtain exception information like formats of results and prints the text.
Example:
import sys
import random
numberlist = ['a', 2, 2]
for number in numberlist:
try:
print("The 1st number is", number)
r = 1+int(number)
break
except:
print("k", sys.exc_info()[0], "value.")
print("Next entry.")
print("The addition of", number, "is", r)
Below screenshot shows the output:
Python catch different exception types
Now, we can see how to catch different exception types in python.
- In this example, I have imported a module called sys, and try block is used to identify the error.
- The division operation is performed, as the zero can’t be divided by any number ZeroDivisionError occur except is executed and “The zero can’t be divided” is displayed.
- The addition operation is performed as the input is given in the string format so the error is generated and as the exception is given as TypeError.
- So the except is executed and displayed as ‘The number is in the string format‘.
Example:
import sys
try:
n = 0
m = 2
c = m/n
except(ZeroDivisionError) as e:
print("The zero can't be divided")
try:
n = 2
m = '3'
p = m+n
except TypeError:
print('The number is in the string format')
You can refer to the below screenshot for the output:
Python catch multiple exceptions in one line
Now, we can see how to catch multi exception in one line in python.
- In this example, I have imported a module called sys, try block is used and declared a variable as a number.
- Here, number = number+’5′ and assigned multiple exceptions in one line in the except and except is executed.
Example:
import sys
try:
number = 2
number = number+'5'
except(TypeError, SyntaxError, ValueError)as e:
print("The number is given in string format")
You refer to the below screenshot for the output:
Python catch-all exceptions
Now, we can see how to catch all exceptions in python.
- In this example, I have taken all exceptions by taking different except for different examples.
- I have used try block to check the errors and used excepts if the error is present excepts are executed.
Example:
try:
print(python)
except NameError:
print("python is not defined")
try:
list = [1,2,3]
print(list[5])
except IndexError as e:
print(e)
print("index error")
try:
from cv import numpy
except Exception:
print("improper module")
try:
print(hello)
except:
print("hello is not defined")
finally:
print(" The finally is executed")
try:
print(chair)
except NameError:
print ("NameError:'cot' is not defined")
else:
print ("word found no error")
The below screenshot shows the output.
Python handle different exception types
Now, we can see how to handle different exception types in python.
- In this example, I have taken three different exception types as except ZeroDivisionError, except TypeError, and except Exception.
- I have used try block to check the errors and used excepts if the error is present excepts are executed.
Example:
try:
n = 0
m = 3
c = m/n
except(ZeroDivisionError) as e:
print("The zero can't be divided")
try:
n = 2
m = 'HEllo'
p = m+n
except TypeError:
print('The number is in the string format')
try:
from cv import pandas
except Exception:
print("improper module")
Below screenshot shows the output with examples that is having different excepts in it.
Catch multiple exceptions python3
Now, we can see how to Catch multiple exceptions python3.
- In this example, I have used multiple exceptions like except TypeError, except, except SyntaxError as e.
- All these multiple exceptions are used with different examples.
- I have used try block to check the errors and used excepts if the error is present excepts are executed.
Example:
try:
print(x)
except TypeError:
print("x is not defined")
except:
print("Error")
try:
print(a+b)
except:
print("exception occured")
try:
print(hello)
except SyntaxError as e:
print("Invalid syntax")
except:
print("Invalid syntax")
Below screenshot shows the output:
User-defined exceptions in python
Here, we can see User-defined exceptions in python.
- In this example, I have defined the class as class Number(Exception) and another two classes are to define exceptions to create two errors such as class SmallNumberError(Number).
- Another error is class LargeNumberError(Number), while a condition is true I have used try block, and if condition is not satisfied except is executed.
Example:
class Number(Exception):
pass
class SmallNumberError(Number):
pass
class LargeNumberError(Number):
pass
number = 5
while True:
try:
Input = int(input("Enter a number: "))
if Input < number:
raise SmallNumberError
elif Input > number:
raise LargeNumberError
break
except SmallNumberError:
print("The number is small")
print()
except LargeNumberError:
print("The number is large")
When condition is not true the userdefined exception is executed. You can refer to the below screenshot for the output:
Customized Excepting classes
Now, we can see how to customized Excepting Classes in python.
- In this example, We have overridden the constructor of the Exception class to pass the arguments such as self, cash, message.
- Then constructor of the parent exception class is called by using self.message by using super(). The attribute self.cash is defined.
- To get the error message, I have written Cash is not in (2000, 1000) range.
Example:
class CashNotInRangeError(Exception):
def __init__(self, cash, message="Cash is not in (2000, 1000) range"):
self.cash = cash
self.message = message
super().__init__(self.message)
cash = int(input("Enter cash: "))
if not 2000 < cash < 1000:
raise CashNotInRangeError(cash)
The below screenshot shows the ouput:
You may like the following python tutorials:
- What is a Python Dictionary + Create a dictionary in Python
- Python print without newline
- Python Dictionary Methods
- How to create a list in Python
- How to convert an integer to string in python
- How to concatenate strings in python
- How to split a string using regex in python
- Python intersection of sets
In this tutorial, we have learned about Python catch multiple exceptions, and also we have covered these topics:
- Python catching exceptions
- Python catch different exception types
- Python catch multiple exceptions in one line
- Python catch-all exceptions
- Python handle different exception types
- Catch multiple exceptions python3
- User-defined exceptions in python
- Customized Excepting classes
Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.