Separating except portion of a try/except into a function

Question:

I have a try/except where I repeat the except portion frequently in my code. This led me to believe that it would be better to separate the except portion into a function.

Below is my use case:

try:
  ...
except api.error.ReadError as e:
  ...
except api.error.APIConnectionError as e:
  ...
except Exception as e:
  ...

How would I go about separating this logic into a function so I can do something as simple as:

try:
  ...
except:
  my_error_handling_function(e)
Asked By: Michael Smith

||

Answers:

Just define the function:

def my_error_handling(e):
    #Do stuff

…and pass in the exception object as the parameter:

try:
    #some code
except Exception as e:
    my_error_handling(e)

Using just a generic Exception type will allow you to have a single except clause and handle and test for different error types within your handling function.

In order to check for the name of the caught exception, you can get it by doing:

type(e).__name__

Which will print the name, such as ValueError, IOError, etc.

Answered By: m_callens

Define your function:

def my_error_handling(e):
    #Handle exception

And do what you’re proposing:

try:
  ...
except Exception as e:
  my_error_handling_function(e)

You can handle logic by getting the type of the exception ‘e’ within your function. See: python: How do I know what type of exception occurred?

Answered By: Checkmate

I would suggest refactoring your code so the try/except block is only present in a single location.

For instance, an API class with a send() method, seems like a reasonable candidate for containing the error handling logic you have described in your question.

Answered By: David Smith

If you don’t like try-catch statement, you can use exception-decouple package and decorator.

from exception_decouple import redirect_exceptions

def my_error_handling(arg, e):
    #Do stuff

@redirect_exceptions(my_error_handling, api.error.ReadError, api.error.APIConnectionError)
def foo(arg):
    ...
Answered By: Aleksandr Gavrilov
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.