Python Ignore Exception and Go Back to Where I Was

后端 未结 7 1382
孤街浪徒
孤街浪徒 2021-02-13 12:47

I know using below code to ignore a certain exception, but how to let the code go back to where it got exception and keep executing? Say if the exception \'Exception\' raises in

7条回答
  •  情歌与酒
    2021-02-13 13:05

    I posted this recently as an answer to another question. Here you have a function that returns a function that ignores ("traps") specified exceptions when calling any function. Then you invoke the desired function indirectly through the "trap."

    def maketrap(*exceptions):
        def trap(func, *args, **kwargs):
            try:
                return func(*args, **kwargs)
            except exceptions:
                return None
        return trap
    
    # create a trap that ignores all exceptions
    trapall = maketrap(Exception) 
    
    # create a trap that ignores two exceptions
    trapkeyattrerr = maketrap(KeyError, AttributeError)
    
    # Now call some functions, ignoring specific exceptions
    trapall(dosomething1, arg1, arg2)
    trapkeyattrerr(dosomething2, arg1, arg2, arg3)
    

    In general I'm with those who say that ignoring exceptions is a bad idea, but if you do it, you should be as specific as possible as to which exceptions you think your code can tolerate.

提交回复
热议问题