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

前端 未结 3 1088
南笙
南笙 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:06

    In your case, the exception in worker returns None. Once that happens, there's no getting the exception back. If your master function knows what the return values should be for each function (for example, ZeroDivisionError in worker reutrns None, you can manually reraise an exception.

    If you're not able to edit the worker functions themselves, I don't think there's too much you can do. You might be able to use some of the solutions from this answer, if they work in code as well as on the console.

    krflol's code above is kind of like how C handled exceptions - there was a global variable that, whenever an exception happened, was assigned a number which could later be cross-referenced to figure out what the exception was. That is also a possible solution.

    If you're willing to edit the worker functions, though, then escalating an exception to the code that called the function is actually really simple:

    try: 
        # some code
    except:
        # some response
        raise
    

    If you use a blank raise at the end of a catch block, it'll reraise the same exception it just caught. Alternatively, you can name the exception if you need to debug print, and do the same thing, or even raise a different exception.

    except Exception as e:
        # some code
        raise e
    

提交回复
热议问题