Interview question
How do you catch multiple exceptions in Python? Python में multiple exceptions कैसे catch करें?
Answer
# Catching multiple exception types with one handler
try:
value = int(input('Enter a number: '))
result = 10 / value
except (ValueError, ZeroDivisionError) as e:
print(f'Error occurred: {e}')
# Separate handlers for different exceptions - runs top to bottom, first match wins
try:
data = {'a': 1}
print(data['b'])
except KeyError:
print('Key not found')
except ValueError:
print('Invalid value') # not reached, KeyError matched first
except Exception as e:
print(f'Unexpected error: {e}') # catch-all, should be LAST
# Order matters - specific exceptions before general ones
try:
risky_operation()
except ZeroDivisionError:
print('Specific handler')
except Exception:
print('General handler')
# If order was reversed, Exception would catch everything first,
# making the ZeroDivisionError handler unreachable (dead code)# एक handler में multiple exception types catch करना
try:
value = int(input('Enter a number: '))
result = 10 / value
except (ValueError, ZeroDivisionError) as e:
print(f'Error: {e}')
# अलग-अलग exceptions के लिए अलग handlers
try:
data = {'a': 1}
print(data['b'])
except KeyError:
print('Key नहीं मिली')
except ValueError:
print('गलत value')
except Exception as e:
print(f'अनपेक्षित error: {e}') # catch-all, आखिर में होना चाहिए
# Order important है - specific exceptions पहले
try:
risky_operation()
except ZeroDivisionError:
print('Specific handler')
except Exception:
print('General handler')Was this answer clear?