Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catch exception in outer try/except

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?

like image 279
Aditya Avatar asked Dec 05 '25 00:12

Aditya


1 Answers

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.

like image 70
Chris Mueller Avatar answered Dec 07 '25 16:12

Chris Mueller