From ArcPy examples, it seems like
sys.exit() is the correct way to terminate a script early.
The Python documentation notes that
is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.
The easy way to deal with this is to wrap your script in an exception handler:
However, this is not particularly elegant and requires a restructure of your entire project, not to mention another level of indentation. Plus, in the unlikely situation that another part of your code raises a
SystemExit exception you would never know about it... Another inelegant but perhaps preferable solution is to wrap calls to sys.exit() in another function:
Now you can call
finish('Error message') just like you expect to be able to call sys.exit().
Of course, we might want to use our exception eating approach in other circumstances, and because this is Python, we can generalise and make a useful, multipurpose decorator:
def eat_exception(fn, exception):
def safe(*v, **k):
finish = eat_exception(sys.exit, SystemExit)