2

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)
Michael Smith
  • 3,307
  • 5
  • 25
  • 43
  • How about making a custom error class so you can just catch a single kind of error? – Andrew Jaffe Jun 28 '16 at 19:21
  • You don't have to catch each exception separately if they are handled the same: `except (api.error.ReadError, api.error.APIConnectionError, Exception) as e:` If they aren't handled the same, don't use one function to handle them all. – chepner Jun 28 '16 at 19:27

4 Answers4

2

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.

m_callens
  • 6,100
  • 8
  • 32
  • 54
0

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?

Community
  • 1
  • 1
Checkmate
  • 1,074
  • 9
  • 16
0

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.

David Smith
  • 593
  • 2
  • 10
0

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):
    ...