πŸ”₯ 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

Different Cases in try,except and finally blocks in Python

Case-1: If there is no exception

1) try:

2)     print("try")

3) except:

4)     print("except")

5) finally:

6)     print("finally")


Output

try

finally


Case-2: If there is an exception raised but handled


1) try:

2)     print("try")

3)     print(10/0)

4) except ZeroDivisionError:

5)     print("except")

6) finally:

7)     print("finally")


Output

try

except

finally


Case–3: If there is an exception raised but not handled:

1) try:

2)     print("try")

3)     print(10/0)

4) except NameError:

5)     print("except")

6) finally:

7)     print("finally")


Output:o

try

finally

ZeroDivisionError: division by zero (Abnormal Termination)


✅Note:There is only one situation where the finally block won’t be executed, i.e., whenever we are using the os._exit(0) function.


==>Whenever we use the os._exit(0) function, the Python Virtual Machine itself is shut down.

==>In this particular case, the finally block won’t be executed.


1) import os

2) try:

3)     print("try")

4)     os._exit(0)

5) except NameError:

6)     print("except")

7) finally:

8)     print("finally")


Output:

try

✅Note:os._exit(0)

0 represents the status code

It indicates normal termination

Multiple status codes are possible.

No comments:

Post a Comment

Thank you Very Much.For Given Comment

Quatation of the Day 22-03-2026