在外部try / except中捕获异常

时间:2017-11-02 11:21:52

标签: python python-2.7 try-except

在以下代码中,

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()

有没有办法让外部try / except块引发异常而不对内部try / except进行任何更改?

2 个答案:

答案 0 :(得分:2)

您可以链接代码异常,如下所示:

def func():
    try:
        x = 2/0
    except ZeroDivisionError:  # specific exception
        print "Division by zero is not possible"
    except Exception:  # catch all exception
        raise Exception("Exception caught")

答案 1 :(得分:1)

听起来你真正想要做的就是捕获另一个函数引发的异常。为此,您需要从函数中引发异常(即示例中的内部尝试/除外)。

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

请注意,我做了两个重要的更改。 1)我在内部函数中重新引发了错误。 2)我在第二个函数中发现了特定的异常。