views:

1335

answers:

5

I need to stop my program when an exception is raised in Python. How do I implement this?

+3  A: 

As far as I know, if an exception is not caught by your script, it will be interrupted.

Keltia
If it's not caught anywhere, including the wrappers you got there, captain.
ohnoes
+11  A: 
import sys

try:
  print("stuff")
except:
  sys.exit(0)
Loïc Wolff
sys.exit(1) would be more appropriate.
Deestan
This is pure GOTO
Ali A
I'd immediatly fire anyone wrting such code in my team. Either let the exception propagate (it will exit the program if no one in the call stack handle it), or log the exception, display a useful error message to the user and try to _cleanly_ exit.
bruno desthuilliers
@bruno desthuilliersWell, it's pretty obvious. All he asks was the script exiting when an exception occurs.
Loïc Wolff
+7  A: 

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.

Abgan
+1  A: 

If 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 anything to do to make your script exit when an exception happens.

bruno desthuilliers
A: 
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.

Pranab