🔥 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

Free 51 Websites for Learning Education and Courses

🛑 లక్à°·à°²ు à°–à°°్à°šుà°ªెà°Ÿ్à°Ÿి à°•ాà°²ేà°œీà°²్à°²ో à°¨ేà°°్à°šుà°•ోà°²ేà°¨ి à°µిà°·à°¯ాలను, à°«్à°°ీà°—ా à°¨ేà°°్à°ªింà°šే 51 à°…à°¦్à°­ుతమైà°¨ à°µెà°¬్‌à°¸ైà°Ÿ్à°²ు ఇవే! 🛑 à°Žà°¡్à°¯ుà°•ేà°·à°¨్ and à°•ోà°°్à°¸ుà°²ు: Co...