πŸ”₯ Welcome to my blog! Latest updates available now. Visit daily! πŸ”₯ πŸ”₯ Click Here for Latest Updates – Visit My Blog πŸ”₯
πŸ”₯ Latest Updates πŸ“Š GP Grade Finder πŸ“’ Government Services Info πŸ†• New Schemes Updates

How to print exception information in Python

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

Quatation of the Day 22-03-2026