用于异常处理的首选Python样式

ign*_*low 3 python syntax try-except

这是一个一般的,最佳实践问题.以下哪个try-except示例更好(函数本身是requests.get()的简单包装器):

def get(self, url, params=params):
    try:
        response = {}
        response = requests.get(url, params=params)
    except requests.ConnectionError,e:
        log.exception(e)
    finally:
        return response
Run Code Online (Sandbox Code Playgroud)

要么

def get(self, url, params=params):
    try:
        return requests.get(url, params=params)
    except requests.ConnectionError,e:
        log.exception(e)
        return {}
Run Code Online (Sandbox Code Playgroud)

或许两者都不是最理想的?我似乎经常为错误记录编写这些包装函数,并且想知道最恐怖的方式.对此有任何建议将不胜感激.

小智 5

最好不要在异常上返回任何内容,我同意Mark - 没有必要在异常时返回任何内容.

def get(self, url, params=params):
    try:
        return requests.get(url, params=params)
    except requests.ConnectionError,e:
        log.exception(e)

res = get(...)
if res is not None:
    #Proccess with data

#or
if res is None:
    #aborting
Run Code Online (Sandbox Code Playgroud)