Interview question
What is exception chaining and what does 'raise ... from ...' do? Exception chaining क्या है और 'raise ... from ...' क्या करता है?
Answer
Exception chaining preserves the original exception's context when raising a new one in response to it, making debugging easier by showing the full causal chain.
def parse_config(raw_value):
try:
return int(raw_value)
except ValueError as e:
# 'from e' explicitly links the new exception to the original cause
raise ValueError(f'Invalid config value: {raw_value}') from e
try:
parse_config('not_a_number')
except ValueError as e:
print(e)
print(e.__cause__) # the original ValueError, accessible via __cause__
# Without 'from e' - Python still shows BOTH exceptions automatically
# (implicit chaining via __context__) but marks it differently:
# 'During handling of the above exception, another exception occurred'
def parse_config_implicit(raw_value):
try:
return int(raw_value)
except ValueError:
raise ValueError(f'Invalid config value: {raw_value}') # no 'from'
# Suppressing the chain entirely when the original isn't useful context
def parse_silent(raw_value):
try:
return int(raw_value)
except ValueError:
raise ValueError('Invalid config value') from None # hides original tracebackException chaining नया exception raise करते समय original exception का context preserve करता है, पूरी causal chain दिखाकर debugging आसान बनाता है।
def parse_config(raw_value):
try:
return int(raw_value)
except ValueError as e:
raise ValueError(f'Invalid config value: {raw_value}') from e
try:
parse_config('not_a_number')
except ValueError as e:
print(e)
print(e.__cause__) # original ValueError
# 'from e' के बिना भी Python दोनों exceptions दिखाता है (implicit chaining)
def parse_config_implicit(raw_value):
try:
return int(raw_value)
except ValueError:
raise ValueError(f'Invalid config value: {raw_value}')
# Chain को suppress करना
def parse_silent(raw_value):
try:
return int(raw_value)
except ValueError:
raise ValueError('Invalid config value') from NoneWas this answer clear?