try:
print(10/0)
except ZeroDivisionError as msg:
print("exception raised and its description is:", msg)
Output:
exception raised and its description is: division by zero
try with multiple except blocks:
πThe way of handling exception is varied from exception to exception.
πHence,we have to provide separate except block for every exception type.
πThat is, try with multiple except blocks is possible and recommended to use.
Example:
try:
------
------
------
except ZeroDivisionError:
perform alternative arithmetic operations
except FileNotFoundError:
use local file instead of remote file
πIf try with multiple except blocks available, then based on the raised exception, the corresponding except block will be executed.
Example: Multiple except blocks in Python
try:
x = int(input("Enter First Number: "))
y = int(input("Enter Second Number: "))
print(x / y)
except ZeroDivisionError:
print("Can't Divide with Zero")
except ValueError:
print("please provide int value only")
Program Execution:
D:\Python3>py Multi.py
Enter First Number: 10
Enter Second Number: 5
2.0
D:\Python3>py Multi.py
Enter First Number: 10
Enter Second Number: 0
Can't Divide with Zero
D:\Python3>py Multi.py
Enter First Number: 10
Enter Second Number: five
please provide int value only
✅Note: If try has multiple except blocks, the order of the except blocks is important.
πThe Python interpreter always checks from top to bottom and executes the first matching except block.
Example
1) try:
2) x = int(input("Enter First Number: "))
3) y = int(input("Enter Second Number: "))
4) print(x / y)
5) except ArithmeticError:
6) print("ArithmeticError")
7) except ZeroDivisionError:
8) print("ZeroDivisionError")
D:\Python3> py MulEx.py
Enter First Number: 5
Enter Second Number: 0
ArithmeticError
✅Note:
Since ZeroDivisionError is a subclass of ArithmeticError, the except ArithmeticError block will catch it first. That’s why exception order matters in Python.
No comments:
Post a Comment
Thank you Very Much.For Given Comment