Python Exception Handling - Best Practices

﹥>﹥吖頭↗ 提交于 2019-12-23 18:27:34

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/16268086/python-exception-handling-best-practices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!