python catch exception and continue try block

前端 未结 9 2386
眼角桃花
眼角桃花 2020-11-29 00:59

Can I return to executing try-block after exception occurs? (The goal is to write less) For Example:

try:
    do_smth1()
except:
    pass

try:
    do_smth2(         


        
相关标签:
9条回答
  • 2020-11-29 01:23

    You can achieve what you want, but with a different syntax. You can use a "finally" block after the try/except. Doing this way, python will execute the block of code regardless the exception was thrown, or not.

    Like this:

    try:
        do_smth1()
    except:
        pass
    finally:
        do_smth2()
    

    But, if you want to execute do_smth2() only if the exception was not thrown, use a "else" block:

    try:
        do_smth1()
    except:
        pass
    else:
        do_smth2()
    

    You can mix them too, in a try/except/else/finally clause. Have fun!

    0 讨论(0)
  • 2020-11-29 01:26

    special_func to avoid try-except repetition:

    def special_func(test_case_dict):
        final_dict = {}
        exception_dict = {}
    
        def try_except_avoider(test_case_dict):
    
            try:
                for k,v in test_case_dict.items():
                    final_dict[k]=eval(v) #If no exception evaluate the function and add it to final_dict
    
            except Exception as e:
                exception_dict[k]=e #extract exception
                test_case_dict.pop(k)
                try_except_avoider(test_case_dict) #recursive function to handle remaining functions
    
            finally:  #cleanup
                final_dict.update(exception_dict)
                return final_dict #combine exception dict and  final dict
    
        return try_except_avoider(test_case_dict) 
    

    Run code:

    def add(a,b):
        return (a+b)
    def sub(a,b):
        return (a-b)
    def mul(a,b):
        return (a*b)
    
    case = {"AddFunc":"add(8,8)","SubFunc":"sub(p,5)","MulFunc":"mul(9,6)"}
    solution = special_func(case)
    

    Output looks like:

    {'AddFunc': 16, 'MulFunc': 54, 'SubFunc': NameError("name 'p' is not defined")}
    

    To convert to variables:

    locals().update(solution)
    

    Variables would look like:

    AddFunc = 16, MulFunc = 54, SubFunc = NameError("name 'p' is not defined")
    
    0 讨论(0)
  • 2020-11-29 01:28

    I don't think you want to do this. The correct way to use a try statement in general is as precisely as possible. I think it would be better to do:

    try:
        do_smth1()
    except Stmnh1Exception:
        # handle Stmnh1Exception
    
    try:
        do_smth2()
    except Stmnh2Exception:
        # handle Stmnh2Exception
    
    0 讨论(0)
提交回复
热议问题