在什么情况下你应该在函数中使用块try-except,在什么情况下不推荐或根本不可能使用它们?
捕获和处理异常和错误的最佳方法是什么 - 有或没有块?对开发人员的最佳实践感兴趣。
澄清评论。
我参加了课程,我自己在所有功能中都使用了 try 异常。最近,在使用 deno (JS) 时,一位经验丰富的开发人员告诉我根本不要使用try-catch它,除非在代码的情况下我无法预见所有可能的错误。
try-except在这方面,我有一个问题 -在调用某些库的所有函数中使用的正确性和合理性如何?
带有 try except 的函数代码示例。就异常处理而言,它的正确性和最优性如何?
async def GetPrices(symbol, exchange, limit=10):
sellPrice = None
buyPrice = None
while True:
try:
orderBook = await exchange.fetchOrderBook(symbol, limit=limit)
bidsPrice, bidsAmount = map(list, zip(*orderBook['bids']))
asksPrice, asksAmount = map(list, zip(*orderBook['asks']))
buyPrice = np.average(bidsPrice, weights = bidsAmount)
sellPrice = np.average(asksPrice, weights = asksAmount)
break
except ccxt.RequestTimeout as e:
log.error("Exchange %s %s %s", exchange.name, '[' + type(e).__name__ + ']', str(e)[0:200])
# will retry
except ccxt.DDoSProtection as e:
log.error("Exchange %s %s %s", exchange.name, '[' + type(e).__name__ + ']', str(e)[0:200])
# will retry
except ccxt.ExchangeNotAvailable as e:
log.error("Exchange %s %s %s", exchange.name, '[' + type(e).__name__ + ']', str(e)[0:200])
# will retry
except ccxt.ExchangeError as e:
log.error("Exchange %s %s %s", exchange.name, '[' + type(e).__name__ + ']', str(e)[0:200])
break # won't retry
except Exception as e:
log.error("Exchange %s %s %s", exchange.name, '[' + type(e).__name__ + ']', str(e)[0:200])
break # won't retry
return sellPrice, buyPrice
在您在评论中澄清问题后,我想我可以就我认为使用异常处理的正确方法提供一些建议。
在我看来,我们只需要捕获我们想要显式处理的已知异常,并且我们非常清楚在异常发生后该怎么做。
在所有其他情况下,您必须要么不处理异常,要么再次调用
raise以从块中重新引发异常except ...。新手开发人员经常以这种风格编写异常处理程序:这是非常糟糕的风格。经过这样的错误处理,我们完全是盲目的,不明白哪里出了问题,在什么地方,如何处理。这种回溯弊大于利。
一个有意义的异常处理示例:
测试: