尝试在python中捕获编码模式

atx*_*dba 2 python

我正在处理一组第三方python脚本.我注意到这种枚举许多不同Exception类的一般模式,没有采取不同的操作,但记录了将被捕获的异常的字符串表示.

except AttributeError as ae:
        print("Attribute Error while processing the configuration file!\n{0}\n".format( str(ae) ) )
        intReturnValue = 1
    except IndexError as ie:
        print("Index Error while processing the configuration file!\n{0}\n".format( str(ie) ) )
        intReturnValue = 1
    except NameError as ne:
        print("Name Error while processing the configuration file!\n{0}\n".format( str(ne) ) )
        intReturnValue = 1
    except TypeError as te:
        print("Type Error while processing the configuration file!\n{0}\n".format( str(te) ) )
        intReturnValue = 1
    except:
        print("Unexpected error while processing the configuration file!\n{0}\n".format( sys.exc_info()[0] ) )
        intReturnValue = 1
Run Code Online (Sandbox Code Playgroud)

这种模式是某种形式的蟒蛇主义还是仅仅是作者?似乎python允许你有一个通用的case catch块.在这种情况下,使用它并更动态地生成日志消息会不会更简单?

Dan*_*man 6

哇,这是非常糟糕的代码.您当然可以立即捕获一系列异常并记录它们:

except (AttributeError, IndexError, NameError, TypeError) as e:
    print "%s was raised... " % (e.__class__.__name__)
Run Code Online (Sandbox Code Playgroud)

当然,您应该确定该代码需要捕获所有这些不同异常类型的原因.这听起来像处理代码本身严重错误.