Separating Except Portion Of A Try/except Into A Function
Solution 1:
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.
Solution 2:
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.
Solution 3:
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?
Post a Comment for "Separating Except Portion Of A Try/except Into A Function"