Skip to main content
 首页 » 编程设计

python之在 python 中引发延迟异常

2025年02月15日10cloudgamer

我想知道 python 中是否有针对此用例的标准机制:

try: 
    do_a() 
    if something_happens(): 
        raise DelayedException # is really only raised after do_b() 
    do_b() 
except DelayedException as de: 
    # handle de after the entire try/except block completed 

我显然可以将异常信息存储在一个变量中以便稍后处理,但我想知道 python 中是否内置了这样的机制(3.x 是否有所不同)。

编辑: 澄清一下,在我的用例中,异常处理需要 do_b() 的结果。

请您参考如下方法:

是的,但是它很丑:

try: 
    do_a() 
    try: 
        if do_something(): 
            raise DelayedException() 
    finally: 
        do_b() 
except DelayedException: 
    pass