In the following code,
def func():
try:
try: # No changes to be made here
x = 2/0 # No changes to be made here
except ZeroDivisionError: # No changes to be made here
print "Division by zero is not possible" # No changes to be made here
except:
raise Exception("Exception caught")
func()
Is there a way to let the outer try/except block raise the exception without making any changes to the inner try/except?
It sounds like what you actually want to do is catch an exception raised by another function. To do that you need to raise an exception from the function (i.e. inner try/except in the example).
def func1():
try:
x = 2/0
except ZeroDivisionError:
print "Division by zero is not possible"
raise
def func2():
try:
func1()
except ZeroDivisionError:
print "Exception caught"
func2()
# Division by zero is not possible
# Exception caught
Notice that I've made two crucial changes. 1) I've re-raised the error within the inner function. and 2) I've caught the specific exception in the second function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With