user1870035
user1870035

Reputation:

Python Exception Handling - Best Practices

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.

Upvotes: 4

Views: 3533

Answers (1)

Jeff Tratner
Jeff Tratner

Reputation: 17096

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)

Upvotes: 4

Related Questions