问题
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)
回答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.
回答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.
回答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?
来源:https://stackoverflow.com/questions/38084360/separating-except-portion-of-a-try-except-into-a-function