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

Default except block in Python

-->We can use default except block to handle any type of exceptions.

-->In default except block generally we can print normal error messages.


Syntax:


except:

    statements

Example:


try:

    x = int(input("Enter First Number: "))

    y = int(input("Enter Second Number: "))

    print(x / y)

except ZeroDivisionError:

    print("ZeroDivisionError: Can't divide with zero")

except:

    print("Default Except: Plz provide valid input only")



D:\Python3>py Default.py

Enter First Number: 10

Enter Second Number: 0

ZeroDivisionError: Can't divide with zero


D:\Python3>py Default.py

Enter First Number: 10

Enter Second Number: ten

Default Except: Plz provide valid input only


✅Note:

If try has multiple except blocks, then the default except block should be last.

Otherwise, we will get a SyntaxError.

Example (Wrong Order):


try:

    print(10/0)

except:

    print("Default Except")

except ZeroDivisionError:

    print("ZeroDivisionError")



SyntaxError: default 'except:' must be last

✅Note:

The following are various possible combinations of except blocks:

except ZeroDivisionError:

except ZeroDivisionError as msg:

except (ZeroDivisionError, ValueError):

except (ZeroDivisionError, ValueError) as msg:

except:


finally block:


-->It is not recommended to maintain clean up code (Resource Deallocating Code or Resource Releasing code) inside try block because there is no guarantee for the execution of every statement inside try block always.

-->It is not recommended to maintain clean up code inside except block, because if there is no exception then except block won’t be executed.

Hence we required some place to maintain clean up code which should be executed always irrespective of whether exception raised or not raised and whether exception handled or not handled. Such type of best place is nothing but finally block.

Hence the main purpose of finally block is to maintain clean up code.


try:

    Risky Code

except:

    Handling Code

finally:

    Cleanup code


-->The speciality of finally block is it will be executed always whether exception 

raised or not raised and whether exception handled or not handled.


No comments:

Post a Comment

Thank you Very Much.For Given Comment

Quatation of the Day 22-03-2026