How to prevent “too broad exception” in this case?

后端 未结 6 1964
情话喂你
情话喂你 2021-02-05 00:00

I have a list of functions that may fail and, if one fails, I don\'t want the script to stop, but to continue with next function.

I am executing it with something like th

6条回答
  •  旧时难觅i
    2021-02-05 00:40

    Do you perhaps mean that each function can raise different exceptions? When you name the exception type in the except clause it can be any name that refers to an exception, not just the class name.

    eg.

    def raise_value_error():
        raise ValueError
    
    def raise_type_error():
        raise TypeError
    
    def raise_index_error():
        doesnt_exist
    
    func_and_exceptions = [(raise_value_error, ValueError), (raise_type_error, TypeError), 
        (raise_index_error, IndexError)]
    
    for function, possible_exception in func_and_exceptions:
       try:
           function()
       except possible_exception as e:
           print("caught", repr(e), "when calling", function.__name__)
    

    prints:

    caught ValueError() when calling raise_value_error
    caught TypeError() when calling raise_type_error
    Traceback (most recent call last):
      File "run.py", line 14, in 
        function()
      File "run.py", line 8, in raise_index_error
        doesnt_exist
    NameError: name 'doesnt_exist' is not defined
    

    Of course that leaves you with not knowing what to do when each exception occurs. But since you just want to ignore it and carry on then that's not a problem.

提交回复
热议问题