【问题标题】:generic except clause works Exception as ex does not catch exception in python [duplicate]通用的except子句工作异常,因为ex在python中没有捕获异常[重复]
【发布时间】:2020-02-13 10:54:46
【问题描述】:

我有两个文件:

fl_fn1.py 中的内容:

import fl_fn2

def fn1():
    print("hi")
    try:
        fl_fn2.fn2()
    except:
        print("inside except")
    finally:
        print("finally")

fn1()

fl_fn2.py 中的内容:

import sys

def fn2():
    print("fn2")
    sys.exit(0)

现在,当我从 Windows 命令提示符调用 fl_fn1.py 时,例如;

C:\Program Files\Anaconda3\python.exe C:\Users\User1\Desktop\fl_fn1.py

那么我的输出是:

hi
fn2
inside except
finally



但是,当我将 fl_fn1.py 中的异常部分更改为:

except Exception as ex:
    print("inside except")

那么我的输出是:

hi
fn2
finally

异常部分不执行!!!

有人可以解释发生了什么。我是 Python 新手。
提前致谢 :)

【问题讨论】:

    标签: python exception


    【解决方案1】:

    SystemExit 继承自 BaseException 而不是 Exception 所以要捕捉它你需要 except BaseException as e:。这是为了防止通过except Exception as e: 意外捕获异常

    【讨论】:

    【解决方案2】:

    有一些日志可以帮助您了解您的异常类型:

    import sys
    
    def fn1():
        print("hi")
        try:
            fn2()
        except:
            print("Exception type: ",sys.exc_info()[0], " occured.")
            print("Exception inherits from: ", sys.exc_info()[0].__bases__)
            print("inside except")
        finally:
            print("finally")
    
    fn1()
    

    正如@Chris_Rands 在他的回复中提到的,您会收到SystemExit 继承BaseException 的异常。

    【讨论】:

    • 啊谢谢@andnik 我学到了一些新东西。 sys.exc_info()[0].__bases__
    猜你喜欢
    • 2020-02-17
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    相关资源
    最近更新 更多