Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 1 of 10 · Exception Handling & Debugging
Interview question

How does try/except/else/finally work in Python? Python में try/except/else/finally कैसे काम करता है?

Answer
BlockRuns when
tryContains code that might raise an exception
exceptOnly if an exception occurs in try
elseOnly if NO exception occurred in try
finallyAlways, regardless of exception or not (cleanup)
def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print('Cannot divide by zero')
        return None
    else:
        print('Division succeeded')  # only runs if no exception
        return result
    finally:
        print('Cleanup runs always')  # always runs

divide(10, 2)
# Division succeeded
# Cleanup runs always

divide(10, 0)
# Cannot divide by zero
# Cleanup runs always

# finally runs even if the function returns from inside try/except
def test():
    try:
        return 'from try'
    finally:
        print('finally still runs before returning')
test()  # prints the finally message, then returns 'from try'
Blockकब चलता है
tryException आ सकता है ऐसा code
exceptसिर्फ exception आने पर
elseसिर्फ कोई exception न आए तो
finallyहमेशा (cleanup)
def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print('Zero से divide नहीं हो सकता')
        return None
    else:
        print('Division सफल')
        return result
    finally:
        print('Cleanup हमेशा चलता है')

divide(10, 2)
divide(10, 0)

Was this answer clear?