How do I stop a program when an exception is raised in Python?

PythonException Handling

Python Problem Overview


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

Python Solutions


Solution 1 - Python

import sys

try:
  print("stuff")
except:
  sys.exit(1) # exiing with a non zero value is better for returning from an error

Solution 2 - Python

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.

Solution 3 - Python

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

Solution 4 - Python

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.

Solution 5 - Python

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

Solution 6 - Python

import sys

try: 
	# your code here
except Exception as err:
	print("Error: " + str(err))
sys.exit(50) # whatever non zero exit code

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser46646View Question on Stackoverflow
Solution 1 - PythonLoïc WolffView Answer on Stackoverflow
Solution 2 - PythonAbganView Answer on Stackoverflow
Solution 3 - Pythonbruno desthuilliersView Answer on Stackoverflow
Solution 4 - PythonPranabView Answer on Stackoverflow
Solution 5 - PythonKeltiaView Answer on Stackoverflow
Solution 6 - PythonGyuri789View Answer on Stackoverflow