Interview question
What is the difference between raise, raise Exception, and re-raising a caught exception with bare raise? raise, raise Exception, और caught exception को bare raise से re-raise करने में क्या अंतर है?
Answer
| Usage | Effect |
|---|---|
| raise SomeError('msg') | Raises a new exception with a fresh traceback starting here |
| raise (bare, inside except) | Re-raises the CURRENTLY caught exception, preserving its original traceback |
| raise from | Raises a new exception while explicitly linking to the original cause |
def process(value):
try:
return 100 / value
except ZeroDivisionError:
print('Logging the error before re-raising')
raise # bare raise - re-raises the SAME ZeroDivisionError with original traceback
try:
process(0)
except ZeroDivisionError:
print('Caught it again at a higher level')
# Common pattern: log/handle partially, then let the caller decide what to do
def risky_operation():
try:
do_something_risky()
except ValueError as e:
log_error(e)
raise # don't swallow the error, let it propagate after logging
# Contrast: creating a NEW exception loses the original traceback context
# unless you use 'raise NewError(...) from e'
def process_wrapped(value):
try:
return 100 / value
except ZeroDivisionError as e:
raise RuntimeError('Processing failed') from e # new exception, cause preserved| Usage | Effect |
|---|---|
| raise SomeError('msg') | नया exception, नया traceback |
| raise (bare, except के अंदर) | Currently caught exception को उसी traceback के साथ re-raise करता है |
| raise from | नया exception, original cause से link करते हुए |
def process(value):
try:
return 100 / value
except ZeroDivisionError:
print('Re-raise से पहले log करना')
raise # bare raise - same exception, original traceback
try:
process(0)
except ZeroDivisionError:
print('ऊपर फिर से caught हुआ')
def risky_operation():
try:
do_something_risky()
except ValueError as e:
log_error(e)
raise # error को swallow मत करो
def process_wrapped(value):
try:
return 100 / value
except ZeroDivisionError as e:
raise RuntimeError('Processing fail हुआ') from eWas this answer clear?