🔥 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

à°†ంà°§్à°°à°ª్à°°à°¦ేà°¶్‌à°²ో సదరం సర్à°Ÿిà°«ిà°•ేà°Ÿ్ à°•ోà°¸ం à°Žà°¦ుà°°ుà°šూà°¸్à°¤ుà°¨్à°¨ à°¦ిà°µ్à°¯ాంà°—ులకు à°¸్à°²ాà°Ÿ్ à°¬ుà°•ింà°—్ à°…à°ª్‌à°¡ేà°Ÿ్.

à°‡ంతకుà°®ుంà°¦ు వరకు SADAREM Slot Booking à°ª్à°°à°•్à°°ిà°¯ à°¸్వర్à°£ à°—్à°°ాà°®ం à°¸్వర్à°£ à°µాà°°్à°¡ు à°¦్à°µాà°°ా à°®ాà°¤్à°°à°®ే à°…ంà°¦ుà°¬ాà°Ÿుà°²ో à°‰ంà°¡ేà°¦ి. à°ª్à°°à°¸్à°¤ుà°¤ం à°ª్రజలకు మరింà°¤ à°¸ౌà°•à°°్యవం...