python编写异常处理,Python异常处理 - 最佳实践

I'm writing a python program the accesses a database. I want to catch three types of exceptions when I make a http request. Timeouts, network errors, and http errors. I'm looking for the best way to deal with this situation. I need to check for these exceptions multiple times in multiple areas of my code, and it will look something like this each time:

try:

//some request

except timeout:

print '\nException: Timeout Error'

except connection error:

print '\nException: Network Error'

except http error, e:

print 'Exception: %s.' % e

Since I have to do this multiple times, at least probably 8 or more, should I make a module to handle these exceptions or no? Also in which of these cases would it be advisable to shut my system down as opposed to just displaying a message?

Thank you.

解决方案

If you don't want to use decorators, you can also combine all the except statements, and use some function to handle your exception (assuming that your errors are called TimeoutError, ConnectionError, and HttpError...doesn't really matter for clarity) i.e.

try:

# do stuff

except (TimeoutError, ConnectionError, HttpError) as e:

handle_exception(e)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值