What is the correct or best way to make a python / arcpy script bail out?

812
4
09-19-2014 12:13 AM
NeilAyres
MVP Alum

You know, the script runs, check various inputs and so forth.

If a requirement is not met, eg the feature is not the correct type or something, then bail out and print a meaningful message.

Currently I use sys.exit(), but this is not ideal and throws an error in python.

So, how do the experts do it?

Thanks in advance,

Neil

Tags (2)
0 Kudos
4 Replies
OwenEarley
Occasional Contributor III

The Understanding message types and severity section in the help has some good tips.

Depending on the severity of the issue you can use:

BruceHarold
Esri Regular Contributor

I always used sys.exit()

0 Kudos
JeffWard
Occasional Contributor III

Read the the "Error Handling" page of the help docs.

Jeff Ward
Summit County, Utah
0 Kudos
curtvprice
MVP Esteemed Contributor

If this is a python script tool, it's best to take advantage of parameter validation on the inputs -- to filter the input choices and check inputs before the tool is even run. This makes your tool far easier to use.

Help 10.2: Understanding Validation In Script Tools

If you want to drop out of your script for some other reason - without generating an error, you can create a custom exception and handle it (as suggested by others above):

class HappyError(Exception):

    pass

try:

    # ...

    raise HappyError("message")

    # ...

except HappyError as msg:

    arcpy.AddMessage(msg)

Proper way to declare custom exceptions in modern Python? - Stack Overflow