Interview question
How does try/except/else/finally work in Python? Python में try/except/else/finally कैसे काम करता है?
Answer
| Block | Runs when |
|---|---|
| try | Contains code that might raise an exception |
| except | Only if an exception occurs in try |
| else | Only if NO exception occurred in try |
| finally | Always, 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 | कब चलता है |
|---|---|
| try | Exception आ सकता है ऐसा 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?