How to handle exceptions properly in a pythonic way?

tian.su.yale at gmail.com tian.su.yale at gmail.com
Thu Nov 5 00:02:07 EST 2015


在 2015年11月4日星期三 UTC-6下午10:18:33,zlju... at gmail.com写道:
> > Which would you prefer?
> 
> So if I am just checking for the ConnectionError in get_html and a new exception arises, I will have traceback to the get_html function showing that unhandled exception has happened.
> Now I have to put additional exception block for managing the new exception in the get_html function and I am covered.
> 
> Is that what you wanted to say?

Hi,
If I may, I feel you are trying to address a few separate questions, although they do relate to each other.
1. Coding Design: with the try/except block inside or outside the function
2. Exception Handling: What to do with new un-anticipated exceptions
3. How to record the exception for reference: logging or special value

My feeling is:
1. Personally prefer to put try/except block outside the function, to keep the code clean and easy to follow.
2. I would suggest follow the Test Driven Development (TDD) approach. You are not able to anticipate all types of possible exceptions. However, I'm sure you have a pretty good idea about what exceptions are more likely to happen and cause you problem. In that case, just develop your code to pass these tests, and refactor it in the future if really needed. Not necessary to push your code to be perfect, able to handle every possible exception.
3. Kind of personal choice here, since no matter which way you go, you do need to follow it up and deal with them. Probably I would log it just for record keeping purpose. As long as you follow up and trace back to the root cause, they seem to serve the same goal.
Hope this helps...
All the best,
Tian



More information about the Python-list mailing list