GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing pythonprogramming.net — Python Programming Tutorials Headless Error Handling Python TutorialWelcome to part 23 of the intermediate Python programming tutorial series. In this tutorial, we're going to cover how to handle for errors that occur in a headless/automated program that you're not constantly monitoring. In our previous tutorial, we covered logging with Python, which is very useful, but, if you do hit errors and just return the str(e) of that error, you are likely to find it's not enough useful information, especially if your program is large. If it's a small program, you can probably find the variable it's talking about, like when you get a Let's start with something simple, like: try:
a+b
except Exception as e:
print(str(e))
Here, we get import sys
try:
a+b
except:
print(sys.exc_info()[0])
print(sys.exc_info()[1])
print(sys.exc_info()[2].tb_lineno)
print('Error: {}. {}, line: {}'.format(sys.exc_info()[0],
sys.exc_info()[1],
sys.exc_info()[2].tb_lineno))
In this case, you will see: <class 'NameError'> name 'a' is not defined 4 Error: <class 'NameError'>. name 'a' is not defined, line: 4 Notice that we've simply sliced the values of sys.exc_info(), and we didn't unpack them to variables. As per a StackOverflow comment I read, it would be unwise to unpack them, just in case you get an exception within the exception itself, and you would wind up with a circular reference that never gets garbage collected. Above my head, but apparently that's a thing. Now, we can combine this with logging, and do something like: import sys
import logging
def error_handling():
return 'Error: {}. {}, line: {}'.format(sys.exc_info()[0],
sys.exc_info()[1],
sys.exc_info()[2].tb_lineno)
try:
a+b
except:
logging.error(error_handling())
Output: ERROR:root:Error: <class 'NameError'>. name 'a' is not defined, line: 9 Obviously, you can also configure logging to instead log this to a file. See the logging tutorial in this series for more information there.
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |