4

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 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Out of curiosity, when you do except (timeout, connection_error, http_error) as e:, does that mean that e will be the string "timeout", "connection_error", "http_error", or will it be the actual error? Also if the first part is the case, how do you catch the actual error as well, for example a 404 error or something of that nature?
I was just aping your style. You need the actual errors; however, you can store them as variables. It just means that e stores the exception variable (it's similar to a with statement like with open(path) as e: To be clear, the error will stay the same type as if you did it three separate versions--so if you did except (ValueError, TypeError) as e:, e will be a TypeError or ValueError

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.