尝试python中的catch编码模式
我正在处理一组第三方python脚本。我注意到了这样一种通用模式,即枚举许多不同的异常类,而不采取不同的操作,而是记录将捕获的异常的字符串表示尝试python中的catch编码模式,python,Python,我正在处理一组第三方python脚本。我注意到了这样一种通用模式,即枚举许多不同的异常类,而不采取不同的操作,而是记录将捕获的异常的字符串表示 except AttributeError as ae: print("Attribute Error while processing the configuration file!\n{0}\n".format( str(ae) ) ) intReturnValue = 1 except IndexError
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
这种模式是某种pythonism,还是仅仅是作者?python似乎允许您拥有一个通用的case-catch块。在这种情况下,使用它并更动态地生成日志消息不是更简单吗 哇,这是非常糟糕的代码。您当然可以一次捕获一系列异常并记录它们:
except (AttributeError, IndexError, NameError, TypeError) as e:
print "%s was raised... " % (e.__class__.__name__)
当然,您应该确定为什么代码需要捕获所有这些不同的异常类型。听起来处理代码本身似乎有严重问题。我认为最好像这样做
ERROR_CONDITIONS = AttributeError,IndexError,NameError,TypeError
try:
...
except ERROR_CONDITIONS as ae:
print("Attribute Error while processing the configuration file!\n{0}\n".format( str(ae) ) )
intReturnValue = 1
except:
#unknown errror
写这篇文章的一般方法是
except (AttributeError, IndexError, NameError, TypeError) as ex:
print("{} while processing the configuration file!\n{}\n".format(type(ex).__name, ex)
except BaseException:
print("Unexpected error while processing the configuration file!\n{0}\n".format( sys.exc_info()[0] ) )
或者更好:
except BaseException as ex:
print("{} while processing the configuration file!\n{}\n".format(type(ex).__name, ex)
编辑
捕获BaseException通常是不好的,但并不比一个简单的
更糟糕,除了我本来想说的,但是我必须查找它!太快了,伙计。