user46646
user46646

Reputation: 159261

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

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

Upvotes: 98

Views: 275958

Answers (5)

Loïc Wolff
Loïc Wolff

Reputation: 3312

import sys

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

Upvotes: 93

Abgan
Abgan

Reputation: 3716

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.

Upvotes: 69

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

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.

Upvotes: 29

Pranab
Pranab

Reputation: 2777

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.

Upvotes: 12

Keltia
Keltia

Reputation: 14743

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

Upvotes: 5

Related Questions