I need to stop my program when an exception is raised in Python. How do I implement this?
-
How do you want your program to stop?PEZ– PEZ2009-01-13 13:23:47 +00:00Commented Jan 13, 2009 at 13:23
-
1@Gortok: Thanks for adding [plzsendthecodez] tag. That made my day!S.Lott– S.Lott2009-01-13 13:40:20 +00:00Commented Jan 13, 2009 at 13:40
-
1If we were in C++ land, I would think that you're looking for the equivalent of "catch throw" in GDB. How ever, in Python the exception carries a backtrace telling you exactly where it's thrown from. Is this not enough?user3458– user34582009-01-13 15:03:33 +00:00Commented Jan 13, 2009 at 15:03
5 Answers
import sys
try:
print("stuff")
except:
sys.exit(1) # exiting with a non zero value is better for returning from an error
5 Comments
sys.exit(1) more appropriate..?0 means "finished without errors". Since the sys.exit call appears to be caused by an error, it should yield a program exit code that is not 0. 1 is just a suggestion.You can stop catching the exception, or - if you need to catch it (to do some custom handling), you can re-raise:
try:
doSomeEvilThing()
except Exception, e:
handleException(e)
raise
Note that typing raise without passing an exception object causes the original traceback to be preserved. Typically it is much better than raise e.
Of course - you can also explicitly call
import sys
sys.exit(exitCodeYouFindAppropriate)
This causes SystemExit exception to be raised, and (unless you catch it somewhere) terminates your application with specified exit code.
1 Comment
sys.exc_info() to obtain enough information for a preserved re-raise if some processing is requiredIf you don't handle an exception, it will propagate up the call stack up to the interpreter, which will then display a traceback and exit. IOW : you don't have to do anything to make your script exit when an exception happens.
1 Comment
import sys
try:
import feedparser
except:
print "Error: Cannot import feedparser.\n"
sys.exit(1)
Here we're exiting with a status code of 1. It is usually also helpful to output an error message, write to a log, and clean up.
2 Comments
logging.exception to write the traceback to the log, present the user with meaningful feedback and then bail without reraising the exception.