python how to re-raise an exception which is already caught?

前端 未结 3 1056
南笙
南笙 2021-01-21 07:50
import sys
def worker(a):
    try:
        return 1 / a
    except ZeroDivisionError:
        return None


def master():
    res = worker(0)
    if not res:
        pri         


        
3条回答
  •  一个人的身影
    2021-01-21 08:25

    Not tested, but I suspect you could do something like this. Depending on the scope of the variable you'd have to change it, but I think you'll get the idea

    try:
        something
    except Exception as e:
        variable_to_make_exception = e
    

    .....later on use variable

    an example of using this way of handling errors:

    errors = {}
    try:
        print(foo)
    except Exception as e:
        errors['foo'] = e
    try:
        print(bar)
    except Exception as e:
        errors['bar'] = e
    
    
    print(errors)
    raise errors['foo']
    

    output..

    {'foo': NameError("name 'foo' is not defined",), 'bar': NameError("name 'bar' is not defined",)}
    Traceback (most recent call last):
      File "", line 13, in 
      File "", line 3, in 
    NameError: name 'foo' is not defined
    

提交回复
热议问题