AnsweredAssumed Answered

What is Best Way to Get an Error Message in Python?

Question asked by pmckinneyccpa on Mar 17, 2017
Latest reply on Mar 21, 2017 by blake.terhune

I've been working on developing various Python scripts for the past year.  Typically these are run as scheduled tasks and write the results (successes and/or errors) to a text file.  I pulled my boilerplate code from the ArcGIS documentation.

 

Typically I will use e.message to write the error message. However, there have been a few times when my code in the Except statement writes the line number of the error but not the actual error message.  This has occurred using the FTP module and Shutil module.  It seems to occur with non-Arcpy errors.  After some research, I found alternate code for this (str(e)).  I'm trying to figure out the best way to capture an error message (whether from ArcPy or another module) and write it to the log file.

 

Below is a sample of the two alternatives I've found.  I could also benefit from some understandable reading resources to help me with better handling errors.  It's a nice feature of Python, but I think I've only scratched the surface.

 

Solution #1, which doesn't seem to write error message for non-Arcpy modules:

# Try to run code
# May be ArcPy or another module
Try:

# some code

except Exception, e:
# If an error occurred, write line number and error message to log
tb = sys.exc_info()[2]
report.write("Failed at step 1 \n" "Line %i" % tb.tb_lineno)
report.write(e.message)

 

Solution #2, which seems to work with non-ArcPy modules:

# Try to run code
# May be ArcPy or another module
try:

# Some code

# Catch errors and write error message
except Exception, e:
# If an error occurred, write line number and error message to log
tb = sys.exc_info()[2]
report.write("Failed at Line %i \n" % tb.tb_lineno)
report.write("Error: {}".format(str(e)))

Outcomes