Select to view content in your preferred language

Raising exceptions in a Python thread

870
2
05-21-2013 03:43 AM
JamesCrandall
MVP Frequent Contributor
Ok I'm a newbie in this area so I need to understand how exceptions are raised...
Below is my Add-in code which is essentially the example for a button on a toolbar in the ArcGIS 10.1 Python wizard help.
I've added the error handling.....
So the problem is that nothing happens - the button does not work but neither are there any exceptions raised...
So what am I doing wrong? The add-in toolbar appears in the project, the button is enabled but no exceptions appear in the python window and I have no indication the code is executing.

import arcpy
import pythonaddins

class ButtonClass11(object):
    """Implementation for test_addin.button (Button)"""
    def __init__(self):
        self.enabled = True
        self.checked = False
try:
# Implementation of OnClick method of Button's class
    def onClick(self):
        # Get the current map document and the first data frame.
        mxd = arcpy.mapping.MapDocument('current')
        df = arcpy.mapping.ListDataFrames(mxd)[0]
        # Call the zoomToSelectedFeatures() method of the data frame class
        df.zoomToSelectedFeatures()
    pass
except Exception, e:
    traceback.print_exc()


Maybe a dumb question, but do you have any features selected when you click the button?

You can also put a print statement before and after the line you expect to 'do stuff'.  In the code above, you can test the zoomToSelectedFeatures method like so,

print "...attempting to run zoomToSelected"
# Call the zoomToSelectedFeatures() method of the data frame class
df.zoomToSelectedFeatures()
print "...finished running zoomToSelected"


This will output the two statements in the Python window when you click the add-in button.  Just a quick and dirty way to debug.
Tags (2)
0 Kudos
2 Replies
JasonScheirer
Esri Alum
Indentation error. Putting the try: statement at that indent level implicitly takes you out of the class definition and just defines an onClick function not bound to anything. Make it look like this:
import arcpy
import pythonaddins
import traceback

class ButtonClass11(object):
    """Implementation for test_addin.button (Button)"""
    def __init__(self):
        self.enabled = True
        self.checked = False
    def onClick(self):
        try:
            # Get the current map document and the first data frame.
            mxd = arcpy.mapping.MapDocument('current')
            df = arcpy.mapping.ListDataFrames(mxd)[0]
            # Call the zoomToSelectedFeatures() method of the data frame class
            df.zoomToSelectedFeatures()
        except Exception as e:
            traceback.print_exc()
0 Kudos
ColinConstance
Emerging Contributor
Thanks!;)
     Now thats a lesson in indentation I hopefully won't forget..
0 Kudos