繁体   English   中英

Python:仅在未捕获时执行异常代码

[英]Python: Execute Exception code only if not caught

假设我想让一个异常总是触发一些代码,比如写一个文件或调用一个外部程序,但前提是它没有被捕获。 我怎样才能做到这一点?

一个不工作的例子:

class MyError(Exception):
    def __init__(self):
        with open('foo.txt', 'a') as stream:
            stream.write("Something bad happened.\n")

try:
    raise MyError()
except:
    print("Just kidding.")

将代码放在围绕整个脚本的try/except块中。

try:
    main()
except MyError:
    with open('foo.txt', 'a') as stream:
        stream.write("Something bad happened\n")

如果main()中的任何内容捕获了异常,则不会在此处捕获,因此不会记录任何内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM